Replies: 3 comments 4 replies
-
|
Right off hand I can only think of using a custom auth middleware or maybe guards to exclude a few routes like |
Beta Was this translation helpful? Give feedback.
-
|
Would the |
Beta Was this translation helpful? Give feedback.
-
|
I put this answer on StackOverflow, but I'll reiterate here as well. My solution to this was to set exclude_from_auth=True on the endpoint, and define a function to check the request for a valid token and authorize the requester if one was found. def authenticate_manually(request: Request) -> User | None:
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer "):
return None
try:
token_str = auth_header[7:]
token = Token.decode(
token_str, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM
)
DB.get_user(token.sub)
except (KeyError, ValueError, NotFoundException):
return None
@get("/some-path", exlude_from_auth=True)
def some_route_handler(request: Request[User, Token, Any]) -> Any:
user = authenticate_manually(request)
if user:
pass # Set some data based on the user
else:
pass # Set data to a hardcoded valueI like @provinzkraut's idea, it is probably possible to rework this as a dependency which would be a cleaner solution IMO. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I have implemented JWTCookieAuth authentication as per tutorials:
https://docs.litestar.dev/2/usage/security/jwt.html
Now, for my app, I would like to redirect user if they are or are not authenticated or appropriate pages, for instance:
which, if user is already logged, redirect user to App. If not, it redirects user to a login page.
Or consider an endpoint
/mewhich could return user name if user is logged and None otherwise.The problem I am getting is that:
useris even trying to be accessed, irrespective if the user is or is not already authenticated, and as I understand it, the user is not even injected into the request even if the user is authenticated.How are these cases handled? I briefly looked at guards, but haven't tried to implement them yet.
There is question on Stackoverflow, but so far without answers.
https://stackoverflow.com/questions/79828650/how-to-enable-endpoints-with-optional-authentication-using-the-litestar-framewor
Beta Was this translation helpful? Give feedback.
All reactions