How to create a remember me function for JWTAuth? #547
-
Hello, first of all thanks for maintaining fastapi-users Now, my problem is that i made a login with the remember me button and in case it is checked on a fastapi route it sets a variable with 1209600 that are going to be the lifetime_seconds of JWT and sets a cookie and then returns the value I know this could be redundant but i've tried all those ways even using globals but that leads to some weird bugs. I'll paste what i have right now
on lifetime_seconds i had |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Hi there! BackgroundFirst of all, rather than a JWT authentication, I think you need a Cookie authentication. It'll be way easier to manage its lifetime then. Now if you look at how to configure this authentication backend: cookie_authentication = CookieAuthentication(secret=SECRET, lifetime_seconds=3600) The property *If you use static-type checking with ProposalNow, I understand that you want either a session cookie or a permanent cookie depending on if the user has checked the Remember me checkbox. This is not something that you could do out-of-the-box right now. However, here is a workaround you could try. You can have two authentication backends, one configured with session cookie and one configured with permanent cookie: session_authentication = CookieAuthentication(name="session", secret=SECRET, lifetime_seconds=None)
cookie_authentication = CookieAuthentication(secret=SECRET, lifetime_seconds=86400) Then, you wire two login routers for both of them: app.include_router(
fastapi_users.get_auth_router(session_authentication), prefix="/auth/session", tags=["auth"]
)
app.include_router(
fastapi_users.get_auth_router(cookie_authentication), prefix="/auth/cookie", tags=["auth"]
) In your webpage, you then just have to call |
Beta Was this translation helpful? Give feedback.
Hi there!
Background
First of all, rather than a JWT authentication, I think you need a Cookie authentication. It'll be way easier to manage its lifetime then.
Now if you look at how to configure this authentication backend:
The property
lifetime_seconds
is here to specify how long this cookie will be stored in the browser. If you set this value toNone
*, it'll mean it's a session cookie (https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#define_the_lifetime_of_a_cookie) that will be deleted when the user closes its browser. If you set a value, like86400
, the browser will remember it for 86400 seconds.