3👍
As others on this thread already suggested, the major point is not storing JWT in your database. It is meant for stateless authentication. You should be able to generate and retrieve the tokens using a secret.
One way to accomplish this in Django is using the SECRET_KEY
to encode and decode the data in JWT like:
import jwt
from django.conf import settings
from django.contrib.auth import get_user_model
from your_project import custom_exceptions as exc
def get_token_for_user(user, scope):
"""
Generate a new signed token containing
a specified user limited for a scope (identified as a string).
"""
data = {
"user_%s_id" % (scope): str(user.id),
}
return jwt.encode(data, settings.SECRET_KEY).decode()
def get_user_for_token(token, scope):
"""
Given a selfcontained token and a scope try to parse and
unsign it.
If max_age is specified it checks token expiration.
If token passes a validation, returns
a user instance corresponding with user_id stored
in the incoming token.
"""
try:
data = jwt.decode(token, settings.SECRET_KEY)
except jwt.DecodeError:
raise exc.NotAuthenticated("Invalid token")
model_cls = get_user_model()
try:
user = model_cls.objects.get(pk=data["user_%s_id" % (scope)])
except (model_cls.DoesNotExist, KeyError):
raise exc.NotAuthenticated("Invalid token")
else:
return user
The function get_token_for_user
would bind the user_id
and scope
of the token together and encode it using the secret key. One might be able to only decode it if the SECRET_KEY
is known.
get_token_for_user
& get_user_for_token
are the utility function you can use once you get the Token from your HTTP_AUTHORIZATION
header to verify if the token is successfully decoded and valid.
These utility function also support a scope
for each token you create. So, for example, you can say that this particular token is just for authentication
and mention the scope as authentication
.
The scope
parameter accepted by these utility function is just a string, so you can use whatever scope you can think of, and while decoding it for a particular API call, you know what scope the token should be available in.
You can modify these as you desire to support JWT for authentication.
2👍
As @Vijesh mentioned in his comment, storing JWT token is not the right approach. From the DRF documentation,
Unlike the built-in TokenAuthentication scheme, JWT Authentication
doesn’t need to use a database to validate a token.
Since you are using django-rest-framework-jwt package for the JWT token authentication. You can also use its apis for retrieving or refreshing the token.
In scenarios where username & password cannot be provided for retrieving or refreshing one should use protected url with JWT token in Authorization header. So after login, construct Authorization header with the token received. (note don’t miss the JWT part in the header)
Authorization: JWT <your_token>
Curl Sample
curl -H "Authorization: JWT <your_token>" http://localhost:8000/protected-url/
- [Django]-Django multi tenancy
- [Django]-How to get django form value in javascript without saving it into model
- [Django]-Django over https form redirection issues
2👍
A major point of using JWT is you don’t want to store tokens in your database. Storing jwt will defeat the purpose of stateless authentication.
You just validate the token and cryptography takes care of the rest.The secret used to create, JWT verifies it against any hampering. Further, It is required that you implement jwt implementation over ssl, to avoid token hijacking.
You don’t typically store any secure data in JWT, but you can if you want by encrypting the payload. As mentioned in JWE specification.
- [Django]-How do I upload Pillow processed image to S3 on Django?
- [Django]-How to install Mezzanine on Webfaction Server
- [Django]-Unicode issue with makemessages –all Django 1.6.2 Python 3.3
- [Django]-How to use django default group permission in django-graphene?
- [Django]-How can I disable a third party API when executing Django unit tests?