How to use token to validate a Django Rest Framework user login

Asked

Viewed 1,564 times

0

Hello, I’m a little lost when authenticating a user by Django-Rest-framework, I was following the tutorial of the channel Codingentrepreneurs in the video 32 of the Blog API (https://www.youtube.com/watch?v=jEXQqNtjNJc) it explains how to authenticate the user via token with Django-Rest-jwt, but I found it very confusing.. and there goes the question:

1 - How do I use the token to allow user access (login) and so that it can consume all my Apis on mobile?? My project is the same as the tutorial (part of the api)

py serializers.

class UserLoginSerializer(ModelSerializer):
token = CharField(allow_blank=True, read_only=True)
username = CharField(label='Código do Usuário',
                     allow_blank=True, required=False)

class Meta:
    model = User
    fields = ['username', 'password', 'token']
    extra_kwargs = {'password':
                    {'write_only': True
                     }
                    }

def validate(self, data):
    user_obj = None
    username = data.get('username', None)
    password = data['password']
    if not username:
        raise ValidationError('Insira o Código de Usuário!')

    user = User.objects.filter(
        Q(username=username)
    ).distinct()
    if user.exists() and user.count() == 1:
        user_obj = user.first()
    else:
        raise ValidationError('Esse Código de Usuário não é válido!')

    if user_obj:
        if not user_obj.check_password(password):
            raise ValidationError('Credenciais Incorretas!')

        data['token'] = 'Some token Here'

    return data

1 answer

1


Create a view for your login (this view is "ready" thanks to the framework, but if you wanted to customize you can.) 'obtain_jwt_token' will log in and return a token it expects the parameters in the post {'username': string, 'password': string}

from rest_framework_jwt.views import obtain_jwt_token
from rest_framework.views import APIView

class UserLogin(APIView):
permission_classes = ()
authentication_classes = ()

def post(self, request):
    # caso queria fazer alguma personalização faça aqui
    return obtain_jwt_token(request)

Create a url for your login.

from django.conf.urls import url
from core.perfil.api UserLogin

urlpatterns = [
    url(r'^login/$', UserLogin.as_view()),
]

To test you can use PostmanResultado:

Note that my url has been /api/profile/login/, not necessarily your route will be the same. You will configure yours in the urls file. (I believe you already know this).


EDIT: I’ll explain how to have a custom return to the function obtain_jwt_token

In your Django configuration file (py Settings.) you can pass as parameter a proper function to override the default return:

# INFORMAÇÕES DO CONTROLE DE API
JWT_AUTH = {'JWT_RESPONSE_PAYLOAD_HANDLER':'core.perfil.serializers.minha_funcao',}

Note that in the example I gave my function is located in the file of serializers that stay in the core/profile/serializers folder. In your case you can put where you want.

And the "function" can be for example:

def minha_funcao(token, user=None, request=None):
  return {
      'token': token,
      'username': user.username,
      'nome': user.first_name,
  }
  • How do I customize my token, to pass the information I want, for example by default it passes (user_id,username,email,Exp..) how do I pass to the token for example the user image and other user registration information?? so I can decode it later

  • I edited it, see if it helps you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.