After using djangorestframework-jwt in an unsafe way for over year I've finally decided that I would like to get it working in a safer fashion.
I've read everywhere that is not good to save a JWT token in the local client (for example, local storage) and that the best solution is to use HttpOnly cookies instead.
I understood that an HttpOnly cookie is a cookie indeed, that can be saved but not read by the browser. So I thought it could be used like the following:
- get_token: the client requests an authorization token to the server by sending user and password: if user and password are valid the server responds with an httpOnly cookie that can be stored but not read by the client.
- Every request the client does from now on are authorized because inside the HttpOnly cookie there is a valid authorization token.
- refresh_token: once the client needs to refresh the token, it only needs to request a refresh_token: if the sent cookie contains a valid token, the server will respond with an updated HttpOnly cookie with the new token.
I'm now trying to use djangorestframework-jwt by using HttpOnly cookie and the JWT_AUTH_COOKIE configuration seems to be the most fitting one:
You can set JWT_AUTH_COOKIE a string if you want to use http cookies in addition to the Authorization header as a valid transport for the token. The string you set here will be used as the cookie name that will be set in the response headers when requesting a token. The token validation procedure will also look into this cookie, if set. The 'Authorization' header takes precedence if both the header and the cookie are present in the request.
Default is None and no cookie is set when creating tokens nor accepted when validating them.
After giving a string value to JWT_AUTH_COOKIE I received an httpOnly cookie as expected.
The problem:
When I call refreshToken I get the following response:
{"token":["This field is required."]}
True, I'm not sending any token in the request's HEADER and that is what I want since the client isn't supposed to keep it saved anywhere.
And that is where I'm getting confused:
If i'm not wrong from now on every request the client does to the server, the cookie should be added to the request.
Shouldn't the server check the cookie after it sees that no token has been passed in the Header? How is it supposed to work if not like this?
Also posted a Github issue here if anyone wants to contribute for improvements: https://github.com/jpadilla/django-rest-framework-jwt/issues/482
axios.defaults.withCredentials = true
and after receiving the cookie you would have to set the headersaxios.defaults.headers.common['Authorization'] = 'JWT <token>'
– Barnsleydjangrestframework-jwt
isn't behaving the way it's supposed to. I'm usingTokenAuthentication
as ahttponly
cookie, but I'm having trouble dealing with a revoked token client-side because Django returns a 401 if you send the expired token along with the request. – Wertheimer