Django JWT auth: How to get user data?

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

This page explains how to get a token from 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 user data (id, email ..) of user "logged in" from server? If I was using session based authentication, I would just serialize and return request.user

if logged in. I don't understand how the server will know who is who if nothing is auth related.

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

+3


source to share


1 answer


You are using the typical Django authorization mechanism with JWT.

  • You POST with username and password and return a token. Your auth view should have the following permission class:

    from rest_framework.views import APIView
    
    class Authenticate(APIView):
        permission_classes = (AllowAny,)
    
          

  • The next time you submit a token, it passes 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',
    ),
    
          

  • Authentication classes install request.user

    and you can use it as usual



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

You absolutely need to research the JWT refresh token mechanism. Tokens are usually short-lived, the default is 5 minutes.

+7


source







All Articles