Abhishek Sachan
Abhishek Sachan

Reputation: 995

Authentication using JWT in Django

what I am trying to do is authenticate my Django project using JWT. Firstly i am confused which library i have to install one is django-jwt-auth and other one is djangorestframework-jwt.

So here is my views.py, in which i have a user model and i want to authenticate when a new user is being generated.

class UserDetails(APIView):

def get(self, request, *args, **kwargs):
    users = Users.objects.all().order_by('-created_at')
    serializer = UserSerializer(users, many=True)
    return Response(serializer.data)

def options(self, request, *args, **kwargs):
    return Response()

def post(self, request, *args, **kwargs):
    serializer = UserSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(status=HTTP_201_CREATED)
    return Response(status=HTTP_400_BAD_REQUEST)

I have models.py

class Users(models.Model):
group_id = models.IntegerField()
name = models.CharField(max_length=100, null=True)
email = models.CharField(max_length=100, null=True)
password = models.CharField(max_length=255, null=False)
remember_token = models.CharField(max_length=255, null=True)
activated = models.IntegerField(default=1)
banned = models.IntegerField(default=0)
ban_reason = models.CharField(max_length=255, null=True)
otp = models.CharField(max_length=255, null=True)
created_at = models.DateTimeField()
updated_at = models.DateTimeField(null=True)

my url.py

urlpatterns = [
url(r'^api-token-auth/', 'rest_framework_jwt.views.obtain_jwt_token'),
url(r'userdetails/$', UserDetails.as_view()),

Now i don't know how to access that api-token-auth. where to put authentication in views.py

and where i ahve to add these settings

JWT_ENCODE_HANDLER = 'jwt_auth.utils.jwt_encode_handler'
JWT_DECODE_HANDLER = 'jwt_auth.utils.jwt_decode_handler',
JWT_PAYLOAD_HANDLER = 'jwt_auth.utils.jwt_payload_handler'
JWT_PAYLOAD_GET_USER_ID_HANDLER = 'jwt_auth.utils.jwt_get_user_id_from_payload_handler'
JWT_SECRET_KEY: SECRET_KEY
JWT_ALGORITHM = 'HS256'
JWT_VERIFY = True
JWT_VERIFY_EXPIRATION = True
JWT_LEEWAY = 0
JWT_EXPIRATION_DELTA = datetime.timedelta(seconds=300)
JWT_ALLOW_REFRESH = False
JWT_REFRESH_EXPIRATION_DELTA = datetime.timedelta(days=7)
JWT_AUTH_HEADER_PREFIX = 'Bearer'

and some post say i have to this to my settings.py

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.BasicAuthentication',
    'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}

So please tell me how to use JWT.

Upvotes: 0

Views: 1291

Answers (1)

Jan Giacomelli
Jan Giacomelli

Reputation: 1339

  1. You should install djangorestframework-jwt
  2. Follow steps here
  3. Add this decorators to functions where you want authentication(change GET appropriate to method you are using, add AllowAny to DEFAULT_AUTHENTICATION_CLASSES if you want to have views accessible without auth)

    @api_view(['GET']) @permission_classes((IsAuthenticated, ))

  4. Call api-token-auth/ with username and password to get token

  5. Add token to your request headers when calling permisson protected functions: Authorization: JWT <your_token>"

All settings must be added to settings.py file like described here I see that your User model doesn't extend AbstractUser or BaseUser model. If you want to use JWT auth with Django, in that easy way desribed here, your User model should extend one of those models(I suggest AbstractUser). Therfore Django will manage all auth hard-work for you.

Upvotes: 4

Related Questions