[Python] What are the preferred patterns or best practices for endpoints with optional...

Discussão em 'Python' iniciado por Stack, Novembro 24, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to define endpoints in a Litestar application in which authentication is optional, but am failing to understand how this can be accomplished with the JWTAuth security backend.

    With an endpoint that is excluded from authentication, there is no attempt to authenticate the request whether or not a token was sent. I.e., an approach like this doesn't work:

    async def retrieve_user_handler(token: Token, connection: ASGIConnection[Any, Any, Any, Any]) -> User | None:
    return DB.get_user(token.sub)


    jwt_auth = JWTAuth[User](
    retrieve_user_handler=retrieve_user_handler,
    token_secret=environ.get("JWT_SECRET", "abcd123"),
    )


    @get("/some-path", exlude_from_auth=True)
    def some_route_handler(request: Request[User, Token, Any]) -> Any:
    if request.user:
    pass # Set some data based on the user
    else:
    pass # Set data to a hardcoded value


    app = Litestar(
    route_handlers=[login_handler, some_route_handler],
    on_app_init=[jwt_auth.on_app_init],
    )


    Is it possible to make a small extension or modification to the JWTAuth configuration to enable optional authentication, or will this require defining a custom dependency or middleware to accomplish this?

    Continue reading...

Compartilhe esta Página