michaelvanstraten / actix-jwt-auth-middleware

JSON Webtoken (JWT) middleware for the actix-web framework
https://docs.rs/actix-jwt-auth-middleware/
MIT License
40 stars 16 forks source link

Allow setting the path for the cookie signer. #24

Open HEPOSHEIKKI opened 6 months ago

HEPOSHEIKKI commented 6 months ago

Currently, there is no explicit way of setting the designated path for the returned cookie pair, resulting in the cookie not being recognized by browsers.

Reproduction steps:

Have the following API layout, using the simple example: /v1/auth/login /v1/api/hello

Define the App with

App::new()
    .service(web::scope("/v1")
    .service(login)
    .use_jwt(authority.clone(), web::scope("").service(hello))

Retrieve the login cookie from /auth/login Try to access /v1/api/hello

As you can see, hello will report unauthorized, as the cookie path has been set to /v1/auth, which doesn't cover the api route. image

michaelvanstraten commented 6 months ago

Yes, I can see that this is an issue with the TokenSigner struct.

Nonetheless, you still can create your own cookie using the value provided from TokenSigner::create_signed_token.

Something like this should work for you:

let token = token_signer.create_signed_token(claims, token_lifetime)?;
let cookie = Cookie::build("access_token".to_string(), token)
    .path("/")
    .secure(true)
    .finish();

The TokenSigner::create_access_cookie method is just a convenience wrapper around the above that ensures that the name of the cookie is set correctly.

Maybe it would be better to just return a builder that allows you to set further options on the cookie.

szsdk commented 5 months ago

I found that your workaround only partially addresses my issue. My goal is to enable users to log in and gain full access to the /app/ directory. I want to allow cookies to refresh properly. When a user refreshes the page at /app/foo, the new access cookie is set with the path /app/foo, which causes problems as it cannot be overwritten through a new login process. I have no idea about to modify the cookie gotten from refresh_authorizer.

ovalek commented 4 months ago

I had the same problem with access_token refreshing. I propose to add a method to TokenSigner builder, that would accept closure with CookieBuilder parameter. PR https://github.com/michaelvanstraten/actix-jwt-auth-middleware/pull/26 This would allow us to set Path and other settings.

michaelvanstraten commented 4 months ago

I suggested to @ovalek that rather than adding a new method that would accept a closure to modify the CookieBuilder before it gets built, we should add an initial CookieBuilder as a user-controllable parameter.

Please speak out if you have a use case where a function is required; it could be that I don't see the full picture here.