簡體   English   中英

使用Redis作為會話存儲時,如何在actix-session和PHP應用程序之間共享會話?

[英]How can I share sessions between actix-session and a PHP application when using Redis as session storage?

我想將使用Redis作為會話存儲的PHP網站切換到actix-web。 我遇到的唯一問題是在我的子域之間共享會話。 我有很多服務,只有其中一些會切換到Rust。

用於會議的板條箱已存在

use actix_session::{CookieSession, Session};
use actix_web::{web, App, Error, HttpResponse, HttpServer};

fn index(session: Session) -> Result<&'static str, Error> {
    // access session data
    if let Some(count) = session.get::<i32>("counter")? {
        println!("SESSION value: {}", count);
        session.set("counter", count + 1)?;
    } else {
        session.set("counter", 1)?;
    }

    Ok("Welcome!")
}

fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap(
                CookieSession::signed(&[0; 32]) // <- create cookie based session middleware
                    .secure(false),
            )
            .service(web::resource("/").to(|| HttpResponse::Ok()))
    })
    .bind("127.0.0.1:59880")?
    .run()
}

我的目標是能夠從我的PHP腳本讀取Rust會話。

這是我嘗試過的:

session_name('RustAndPHP'); // I don't have any idea to name the sessions in Rust

session_set_cookie_params(0,"/",".mydomainname.com",FALSE,FALSE);
setcookie(session_name(), session_id(),0,"/","mydomainname.com");
session_start();

最后,我更改了默認cookie:

setcookie( "mysession", "",1,"/" );
setcookie( "PHPSESSID", "",1,"/" );

我不知道Rust中使用的會話格式以及如何與PHP共享它。

actix-session將會話數據序列化為JSON對cookie進行簽名,並將cookie 的名稱設置為actix-session

要進行驗證,請運行最小的cookie-session-example並使用curl發出請求:

$ curl -v localhost:8080
> GET / HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 200 OK
< content-length: 8
< content-type: text/plain; charset=utf-8
< set-cookie: actix-session=ZTe%2Fb%2F085+VQcxL%2FQRKCnldUxzoc%2FNEOQe94PTBGUfc%3D%7B%22counter%22%3A%221%22%7D; HttpOnly; Path=/
< date: Thu, 11 Jul 2019 21:22:38 GMT

使用解碼decodeURIComponent解碼可得出:

> decodeURIComponent("ZTe%2Fb%2F085+VQcxL%2FQRKCnldUxzoc%2FNEOQe94PTBGUfc%3D%7B%22counter%22%3A%221%22%7D")
'ZTe/b/085+VQcxL/QRKCnldUxzoc/NEOQe94PTBGUfc={"counter":"1"}'

據我所知, ZTe/b/085+VQcxL/QRKCnldUxzoc/NEOQe94PTBGUfc=是簽名。

這可能不是您的PHP腳本在做什么,因此您可能想直接使用HttpRequest::headers 例如,通過創建自己的Session類型,然后在處理程序中使用該類型:

use actix_web::{web, App, Error, HttpServer, HttpRequest, HttpResponse, FromRequest};
use actix_web::dev::Payload;
use actix_web::http::header::{COOKIE, SET_COOKIE};
use actix_web::error::ErrorUnauthorized;

fn main() {
    HttpServer::new(|| {
        App::new()
            .route("/set", web::to(set_cookie))
            .route("/get", web::to(get_cookie))
    })
    .bind("127.0.0.1:8000")
    .expect("Cannot bind to port 8000")
    .run()
    .expect("Unable to run server");
}

fn set_cookie() -> HttpResponse {
    HttpResponse::Ok()
        .header(SET_COOKIE, Session::cookie("0123456789abcdef"))
        .body("cookie set")
}

fn get_cookie(session: Session) -> HttpResponse {
    HttpResponse::Ok()
        .header(SET_COOKIE, Session::cookie("new_session_value"))
        .body(format!("Got cookie {}", &session.0))
}

struct Session(String);

impl Session {
    const COOKIE_NAME: &'static str = "my-session";

    fn cookie(value: &str) -> String {
        String::from(Self::COOKIE_NAME) + "=" + value
    }
}

impl FromRequest for Session {
    type Error = Error;
    type Future = Result<Self, Error>;
    type Config = ();

    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
        for header in req.headers().get_all(COOKIE) {
            // check if header is UTF-8
            if let Ok(value) = header.to_str() {
                // split into cookie values
                for c in value.split(';').map(|s| s.trim()) {
                    // split at '='
                    if let Some(pos) = c.find('=') {
                        // is session key?
                        if Self::COOKIE_NAME == &c[0..pos] {
                            return Ok(Session(String::from(&c[(pos + 1)..])));
                        }
                    }
                }
            }
        }
        Err(ErrorUnauthorized("Session cookie missing"))
    }
}

結果(為簡潔起見,刪除了不相關的標題):

$ curl -v localhost:8000/get
< HTTP/1.1 401 Unauthorized
Session cookie missing⏎

$ curl -v localhost:8000/set
< HTTP/1.1 200 OK
< set-cookie: my-session=0123456789abcdef
cookie set⏎

$ curl -v --cookie my-session=0123456789abcdef localhost:8000/get
> Cookie: my-session=0123456789abcdef
>
< HTTP/1.1 200 OK
< set-cookie: my-session=new_session_value
Got cookie 0123456789abcdef⏎

您還可以在瀏覽器中觀察結果,網址為http:// localhost:8000 / sethttp:// localhost:8000 / get

這非常簡單,但是可以完全控制會話cookie。

注意:上面的解決方案不能保護cookie。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM