How Can I Make Django-rest-framework-jwt Return Token On Registration?
Solution 1:
Question 1: To generate tokens manually on registration you can define and make use of a method like this:
import jwt
from rest_framework_jwt.utils import jwt_payload_handler
defcreate_token(user):
payload = jwt_payload_handler(user)
token = jwt.encode(payload, settings.SECRET_KEY)
return token.decode('unicode_escape')
you can add this method to the view and generate the token once the user has been registered and return it in the response.
Question 2: JWT tokens do not need to be stored in the database. You can read more about how JWT works at http://jwt.io/.
Question 3 and 4: To use tokens to limit access to a specific view, especially an APIView or one of its subclasses or a view provided by Django Rest framework, you need to specify the permission classes. for example:
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
classExampleView(APIView):
permission_classes = (IsAuthenticated,)
defget(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
Question 5: One potential loophole while working with Django Rest Framework is the default permissions that you setup from the settings of your application; if for example you AllowAny
in the settings it'll make all the views publicly accessible unless you specifically override the permission classes in each view.
Solution 2:
The Accepted answer has some code that generates token but it doesn't show how to integrate it in serializer/view. Also not sure that manual jwt.encode
is a good modern way of doing this if we already have jwt_encode_handler
to do this. You can create SerializerMethodField
and create tokens there:
token = serializers.SerializerMethodField()
def get_token(self, obj):
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLERjwt_encode_handler= api_settings.JWT_ENCODE_HANDLERpayload= jwt_payload_handler(obj)
token = jwt_encode_handler(payload)
return token
Then add token
field to Meta.fields
.
Post a Comment for "How Can I Make Django-rest-framework-jwt Return Token On Registration?"