简体   繁体   English

JWT 和 Django Rest 框架中的自定义身份验证

[英]JWT and custom authentication in Django Rest Framework

I have written a very basic custom authentication class in order to implement the simple JWT library for my custom authentication needs.我编写了一个非常基本的自定义身份验证 class 以实现简单的 JWT 库以满足我的自定义身份验证需求。

I generate tokens manually and then send the access token to my API.手动生成令牌,然后将访问令牌发送到我的 API。 By default, this would be enough but since I do not use the default Django user Model, I get "User not found".默认情况下,这已经足够了,但由于我不使用默认的 Django 用户 Model,我得到“找不到用户”。 This is because I need to implement a custom authentication backend.这是因为我需要实现自定义身份验证后端。

I need to read that token in order to query the database with the given user id and check if that token is valid as well.我需要读取该令牌以使用给定的用户 ID 查询数据库并检查该令牌是否也有效。 In my example, I have fixed number 2.在我的例子中,我有固定的数字 2。

在此处输入图像描述

class ExampleAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        try:
            user = vAuthUser.objects.get(pk=2) #this should receive the user_id from the token
        except:
            raise AuthenticationFailed('No such user')

        return (user, None)

My API looks like:我的 API 看起来像:

class MyAPI(APIView):
    authentication_classes = (ExampleAuthentication,)
    permission_classes = (IsAuthenticated ,)

   def get()...

Try this:尝试这个:

from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth.models import User
user = User.objects.first()
refresh = RefreshToken.for_user(user)
raw_token = str(refresh.access_token)

jwt_a = JWTAuthentication()
validated_token = jwt_a.get_validated_token(raw_token)
repr(validated_token)
print(validated_token["user_id"])

Here I feed a raw access token to get_validated_token() method of JWTAuthentication class.在这里,我将原始访问令牌提供给 JWTAuthentication class 的get_validated_token()方法。 it returns a dictionary with these keys: token_type , jti , user_id , exp , and their associated values.它返回一个包含以下键的字典: token_typejtiuser_idexp以及它们的关联值。
I've used the default Django User Model for my sample, but it should work with your custom Model.我已经为我的示例使用了默认的 Django 用户 Model,但它应该适用于您的自定义 Model。
There are more useful methods like get_header() .还有更多有用的方法,例如get_header() check this document and this one too.检查这个文件这个文件。

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

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