Search code examples
pythonapiflaskjwtresponse

How to return a bearer JWT token FROM Flask?


How to form a response from Flask python server which would contain the bearer token in the response. More precisely, I am looking to somehow securely propagate the JWT token from Flask python server back to the client (angular page). I can just return it in form of the querystring in GET redirect. What are other possibilities in terms of returning the JWT access token back to the client? I tried setting the response form python, and to set the jwt token in Authorization field, but nothing worked. This is what I tried:

1.

 r = Response(headers={
                 "Authorization": "bearer jwtcntent",
                 "Access-Control-Allow-Origin": "*",
              },
              is_redirect=True,
              url="https://localhost:5000/callback",
 )
 return r
r = redirect("http://localhost:5000/callback")
r.headers = {"authorization": "bearer jwtcntent"}
return r
r = Response(headers={
                 "Authorization": "Bearer jwtcntent",
                 "Access-Control-Allow-Origin": "*",
             },
             allow_redirects=True,
             url="https://localhost:5000/callback",                       
)
return r

Any recommendations?


Solution

  • You can store it in an httponly cookie, but you need to make sure to handle CSRF attacks if you do so. Flask-JWT-Extended has built in support for this which you might find useful, either as a solution or as a reference for whatever you end up doing:

    https://flask-jwt-extended.readthedocs.io/en/stable/token_locations/#cookies

    You can also just send the token back as part of the JSON body and then storing it in local/session storage, which is probably the most common pattern.