3

I'm working with Flask and restful API to handle my user management calls. Example scenario: Let's say I'm using JWTs to secure my reset password end-point. I experimented with a less secure method, for now, where I grab the token as a part of the response from the previous endpoint, and pass it as a bearer token, I still happen to get a 401 Unauthorized error. Although, I can see from client-side debugging, that the token is getting passed in the header. Ideally, I want to send a post request with Authorization HTTP header and Bearer Authentication scheme and pass this token from the httponly cookie.

The following are the questions I have:

Should I store the token in an HttpOnly Cookie or Localstorage? If I'm using an HttpOnly cookie, how can I access my token from inside the ajax call? What's the best way to use JWTs for user-related functionalities (like reset password, email confirm, etc) other than auth?

I want to ensure I don't compromise on security standards while I accomplish all this.

4

1 回答 1

4

To use JWT securely, you must use secure socket layer to protect it in transit over a network (you know, https connections, not plain http). You can encrypt the contents of JWT too, but it is sufficient security to store it in a cookie send them over encrypted channels only, mark as http only, and flag as secure. I believe this is standard practice regarding cookie security. Please note that cookies are sent in headers along with every request. It is a server side technology really. Moreover, an http only cookie can not be read in any modern browser by script, only written to in some browsers.

If your data is mostly needed at the client side, then switch to local storage for its advantages. It doesn't need to go with every network request. You don't need to worry about the data expiring. You have to explicitly delete it. Good or bad? Decide for your own use case. It honors same origin policy. Since you're putting the token in the header of the request, I see no requirement that says you must store them in a cookie. You can just read the token from local storage and put it in the bearer token on each network request.

Cookies store 4KB, localstorage up to 5MB at the time of writing. To gain more confidence, read these:

Local Storage vs Cookies
If you can decode JWT how are they secure?
Store Auth-Token in Cookie or Header?

I'll put a jsfiddle in a followup comment so you can see code that creates, reads, updates, and deletes cookies. That's all you need to be able to read one and use it in an auth header. I did not however set httponly and secure flag. Ironically, the fiddle does not work as a stack snippet due to a security error.

于 2018-07-10T01:19:27.517 回答