Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django JWT auth: How to get user data?

I'm trying to desperately understand how to use JWT auth with Django.

This page explains how to get a token against username and password:

http://getblimp.github.io/django-rest-framework-jwt/

$ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"password123"}' http://localhost:8000/api-token-auth/

Now in order to access protected api urls you must include the Authorization: JWT <your_token> header.

1) How can I get the user details (id, email..) of the "logged in" user from the server? If I used the session based auth I would just serialize and return request.user if it's logged in. I don't understand how the server would know who is who if nothing auth-related is persisted.

2) I don't even understand how the procedure described in that page is safe. Why can't the attacker just hijack the token and do what he wants? As I understood I just get a token and then send the same token back in every request. Is this even real JWT?

like image 765
user2061057 Avatar asked Mar 21 '17 04:03

user2061057


1 Answers

You use the typical Django auth mechanism with JWT.

  • You POST with the username and password and get the token back. Your auth view needs to have the following permission class:

    from rest_framework.views import APIView
    
    class Authenticate(APIView):
        permission_classes = (AllowAny,)
    
  • The next time you sent the token it goes through here:

    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',
    ),
    
  • The authentication classes set request.user and you can use it as you normally do

2) I don't even understand how the procedure described in that page is safe. Why can't the attacker just hijack the token and do what he wants? As I understood I just get a token and then send the same token back in every request. Is this even real JWT?

You absolutely have to investigate the JWT refresh token mechanism. Tokens are usually short lived, the default is 5 minutes I think.

like image 67
Martin Rusev Avatar answered Nov 14 '22 23:11

Martin Rusev