gpt4 book ai didi

python - 如何使用从登录 View 获得的 jwt token 进行身份验证

转载 作者:太空宇宙 更新时间:2023-11-03 21:07:29 25 4
gpt4 key购买 nike

我需要创建 JWT token 身份验证,但我不知道如何做,您能否解释一下如何做得更好或举一些示例?

我的观点:

class UserLogin(generics.CreateAPIView):
"""
POST auth/login/
"""
# This permission class will overide the global permission
# class setting
permission_classes = (permissions.AllowAny,)

queryset = User.objects.all()
serializer_class = TokenSerializer

def post(self, request, *args, **kwargs):
username = request.data.get("username", "")
password = request.data.get("password", "")

user = auth.authenticate(request, username=username, password=password)
if user is not None:
auth.login(request, user)
return Response({
"token": jwt_encode_handler(jwt_payload_handler(user)),
'username': username,
}, status=200)
return Response(status=status.HTTP_401_UNAUTHORIZED)

最佳答案

您正在该 View 中创建 token 。之后,您需要另外两个机制:

  1. 您的客户端应在每次请求时将此 token 发送到 API,在 Authorization header 中,例如:

    Authorization: Bearer your_token
  2. 在 API 方面,您需要使用身份验证类,该类会查找 Authorization header ,获取 token 并对其进行解码,如果 token 有效,则查找与 token 关联的用户实例。

如果您使用库进行 drf jwt 身份验证,它应该有一个您可以使用的身份验证类。如果您手动实现它,则需要自己编写一个身份验证类,该类是 DRF 的 BaseAuthentication 类的子类。它基本上看起来像这样:

class JwtAuthentication(authentication.BaseAuthentication):

def authenticate(self, request):

auth_header = request.META.get('HTTP_AUTHORIZATION')
if auth_header:
key, token = auth_header.split(' ')

if key == 'Bearer':
# Decode the token here. If it is valid, get the user instance associated with it and return it
...
return user, None

# If token exists but it is invalid, raise AuthenticationFailed exception

# If token does not exist, return None so that another authentication class can handle authentication

您需要告诉 DRF 使用此身份验证类。将其添加到您的设置文件中:

REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': [
'path.to.JwtAuthentication',
...
]
}

关于python - 如何使用从登录 View 获得的 jwt token 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55307041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com