简体   繁体   中英

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?

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.

Are you able to implement a regular OAuth flow in your Authorization Server? OAuth flows are standardized and use secure ways of returning an access token to the client.

I don't recommend using the Authorization header for returning responses. This header is a request header, it has no meaning in a response. If you really need to do it through the header you can add Access-Control-Expose-Headers header to let your client read the Authorization header from a response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM