简体   繁体   English

如何使用 Django Rest 框架在 Header 中包含令牌

[英]How to include Token in Header using Django Rest Framework

I am working with Token Authentication using Django REST Framework .我正在使用Django REST Framework进行Token Authentication I am generating a new token during User Registration .我在User Registration期间生成一个新令牌。 I need to pass this token to the frontend including in header .我需要将此令牌传递给前端,包括header These are my code:这些是我的代码:

settings.py:

INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework.authtoken',
    ...
]

urls.py: (project level) urls.py:项目级别)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('accounts.urls')),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),

]

urls.py: (app level) urls.py:应用级别)

urlpatterns = [
    path('signup/', views.Register.as_view({"post":"register"}), name='users'),
    path('login/', views.Login.as_view({"post":"create"}), name='login'),
    path('profile/', views.Profile.as_view({"get":"list"}), name='profile'),

]

views.py:

# Register View
class Register(viewsets.GenericViewSet, mixins.CreateModelMixin,):
   serializer_class = UserRegisterSerializer

   def register(self, request):

      data_dict = self.request.data

      firstname = data_dict['firstname']
      lastname = data_dict['lastname']
      username = data_dict['username']
      email = data_dict['email']
      password = data_dict['password']
      mobile = data_dict['mobile']

      data = userRegistrationModel.objects.create(firstname=firstname, lastname=lastname, username=username, email=email, password=password, mobile=mobile)

      if data:
          user = data.set_password(password)
          data.save()
          token = Token.objects.create(user=data)

          return Response({"message": "Registered Successfully", "code": "HTTP_201_CREATED", "Token": token.key})
      else:
          return Response({"message": "Sorry Try Next Time!!!",  "code": "HTTP_403_FORBIDDEN"})



# Login View
class Login(viewsets.GenericViewSet, mixins.CreateModelMixin,):
    permission_classes = (AllowAny,)
    serializer_class = UserLoginSerializer

    def create(self, request, *args, **kwargs):

        data_dict = self.request.data

        email = data_dict['email']
        password = data_dict['password']

        data = authenticate(email=email, password=password)

        if data:
            users = Token.objects.filter(user=data).first()

            userData = UserRegisterSerializer(data)

            return Response({"message": "Login Successfully",  "code": "HTTP_200_OK", "token": users.key, "user": userData.data})

        else:
            return Response({"message": "Invalid Login",  "code": "HTTP_401_UNAUTHORIZED"})


# Profile View
class Profile(viewsets.ViewSet):
    permission_classes = (IsAuthenticated,)
    serializer_class = UserProfileSerializer

    def list(self, request, pk):
        queryset = userRegistrationModel.objects.get(id=pk)
        serializer_class = UserProfileSerializer
        ...
        ...

This is screenshot of generating the Token这是生成令牌的屏幕截图

Till here (while generating the new Token) it is working perfectly.直到这里(在生成新令牌时)它工作得很好。 Now when I am including this Token in LoginView then it is not validating.现在,当我在LoginViewincluding this Token时,它不会验证。

Is there any best way to send this Token to the frontend by including in header or if we can update the previous Token by new Token in Login View .是否有任何最好的方法通过包含在 header 中to send this Token到前端,或者if we can update in Login View通过新令牌更新以前的令牌。

I am not getting that how to work with Django REST Framework default authtoken .我不知道如何使用Django REST Framework default authtoken Please guide me what is the standard process of using Token Based Authentication.请指导我使用基于令牌的身份验证的标准过程是什么。

You need to pass a token like this in Django rest framework.您需要在 Django rest 框架中传递这样的令牌。

KEY :  Authorization
VALUE : Token <token-value>

in your eg在你的例如

return Response(
    {
        "message": "Login Successfully",
        "code": "HTTP_200_OK",
        "Authorization": "Token "+users.key,
        "user": userData.data
    }
)

curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' curl -X GET http://127.0.0.1:8000/api/example/ -H '授权:令牌 9944b09199c62bcf94186446dd0e4bbdfee'

Refer this https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication请参阅此https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM