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

0

Hello, I'm kind of lost as a user authentication by django-rest-framework, I was following the CodingEntrepreneurs channel tutorial in Blog API 32 video ( link ) it explains how to do user authentication via token with django-rest-jwt, but I found it very confusing .. and la goes the question:

1 - How do I use the token to allow user access (login) and to be able to consume all my APIs in mobile ?? My project is the same as the tutorial (part of api)

serializers.py

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
    
asked by anonymous 03.09.2017 / 18:30

1 answer

1

Create a view for your login (this view is already "ready" thanks to the framework, however if you wanted to customize you can). 'get_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 postman

Noticethatmyurlhas/api/profile/login/,notnecessarilyitsroutewillbethesame.Youwillconfigureyoursintheurlsfile.(Ibelieveyoualreadyknowthis).

EDIT:I'llexplainhowtogetacustomreturnfortheget_jwt_tokenfunction

InyourDjangoconfigurationfile(settings.py)youcanpassasaparameteranownfunctiontooverridethedefaultreturn:

#INFORMAÇÕESDOCONTROLEDEAPIJWT_AUTH={'JWT_RESPONSE_PAYLOAD_HANDLER':'core.perfil.serializers.minha_funcao',}

NotethatintheexampleIgavemyfunctionitislocatedintheserializersfilethatisinthecore/profile/serializersfolder.Inyourcaseyoucanputitwhereyouwant.

And"myfile" can be for example:

def minha_funcao(token, user=None, request=None):
  return {
      'token': token,
      'username': user.username,
      'nome': user.first_name,
  }
    
04.09.2017 / 22:23