Replies: 3 comments 5 replies
-
This seems to meet your requirements? You can implement the logic in get_enabled_backends and dynamically instantiate CookieTransport with the cookie_max_age. |
Beta Was this translation helpful? Give feedback.
-
Yeah I'd like to avoid that, obviously :)
I think so, too. Extending Again, thank you for your thoughts! |
Beta Was this translation helpful? Give feedback.
-
In case anyone is looking for a solution to get a "remember me"/"keep me signed in" flag for a cookie-based login endpoint: I tried hacking this into the existing logic of FastAPI-Users without completely re-implementing any major parts of the library, but there's just no clean enough way to do it IMHO. So I went the "naive" but maintainable way and just wrote a middleware that intercepts requests to the cookie-based login endpoint and modifies the import re
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
class CookieTypeChoiceMiddleware(BaseHTTPMiddleware):
_TRUTHY_VALS = ("true", "on", "1", "yes")
def __init__(
self,
app,
*,
login_path_suffix="/auth/cookie/login",
form_field_name="persistent",
):
super().__init__(app)
self.login_path_suffix = login_path_suffix
self.form_field_name = form_field_name
async def dispatch(self, request: Request, call_next):
await request.body() # make starlette cache the request body
response = await call_next(request) # pass on the request
if request.url.path.endswith(self.login_path_suffix):
# request was to ...<login_path_suffix>
form_data = await request.form()
if form_data.get(self.form_field_name, "").lower() not in self._TRUTHY_VALS:
# the request is missing `form_field_name` or the value is falsy,
# so we have to force any "set-cookie" headers of the response to
# trigger the creation of session cookies instead of persistent cookies
for k, v in response.headers.items():
if k.lower() == "set-cookie":
response.headers[k] = re.sub(
r"Max-Age=\d+ *;* *",
"",
response.headers[k],
flags=re.IGNORECASE,
)
return response This seems to work just fine. EDIT: Of course the downside of this is that this additional parameter will not automatically be reflected in the API schema! |
Beta Was this translation helpful? Give feedback.
-
This is only relevant for a cookie transport. It would be nice to be able to set a boolean param like
rememberMe
(orpersistent
or whatever) when logging in, so in case it'sfalse
the returnedSet-Cookie
header always creates a session cookie but if it'strue
it creates a persistent cookie with the configuredcookie_max_age
.Of course this would require a way to keep the current behavior of
CookieTransport
, so adding an init argment likesession_cookies_by_default: bool = False
that'd have to be set toTrue
to trigger the feature would make this a non-breaking change.Beta Was this translation helpful? Give feedback.
All reactions