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

2024-09-29 22:34:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个非常基本的自定义身份验证类,以实现简单的JWT库来满足我的自定义身份验证需求

然后将访问令牌发送到我的API。默认情况下,这就足够了,但是因为我没有使用默认的Django用户模型,所以我得到了“user not found”。这是因为我需要实现一个自定义的身份验证后端

我需要读取该令牌,以便使用给定的用户id查询数据库,并检查该令牌是否也是有效的。在我的例子中,我固定了数字2

enter image description here

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)

我的API看起来像:

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

   def get()...

Tags: thedjango用户身份验证apiidgetauthentication
1条回答
网友
1楼 · 发布于 2024-09-29 22:34:39

试试这个:

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"])

这里,我向JWTAuthentication类的get_validated_token()方法提供一个原始访问令牌。它返回一个包含以下键的字典:token_typejtiuser_idexp,以及它们的相关值。
我在示例中使用了默认的Django用户模型,但它应该与您的自定义模型一起使用。
还有更有用的方法,如get_header()。也选中this documentthis one

相关问题 更多 >

    热门问题