如何解码和验证 simple-jwt-django-rest-framework 令牌

use*_*549 5 python django-views django-rest-framework django-rest-framework-simplejwt

我正在尝试验证和解码 simple-jwt-django-rest-framework 令牌。我知道我们可以使用 simple-jwt 的验证 api。但我想在我的观点中解码和验证。以下是我正在尝试的当前代码:-

//in views.py

class home(APIView):
   def post(self,request,*args,**kwargs):
      print("request is ",request._request)
      verify_token_response = token_verify(request._request)
      print("status_code is ", verify_token_response.status_code)

      if(verify_token_response.status_code == 200):
        jwt_object  = JWTAuthentication() 
        validated_token = jwt_object.get_validated_token(request._request)
        user            = jwt_object.get_user(validated_token)
        print(user)
    
    return Response({
            'status':True, 
            'message':'home'
            })
Run Code Online (Sandbox Code Playgroud)

此代码适用于我的令牌验证。它正在正确验证令牌,但是当我检索 valiated_token 和用户时,它给了我以下错误:-

{
    "detail": "Given token not valid for any token type",
    "code": "token_not_valid",
    "messages": [
        {
            "token_class": "AccessToken",
            "token_type": "access",
            "message": "Token is invalid or expired"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

Mai*_*shi 14

您可以使用模块JWTAuthentication中的类rest_framework_simplejwt.authentication。它包含一个名为的方法 authenticate(request),该方法接受请求对象,检查令牌的有效性并返回与令牌关联的用户和带有解码后的声明的经过验证的令牌

from rest_framework_simplejwt.authentication import JWTAuthentication
JWT_authenticator = JWTAuthentication()

# authenitcate() verifies and decode the token
# if token is invalid, it raises an exception and returns 401
response = JWT_authenticator.authenticate(request)
if response is not None:
    # unpacking
    user , token = response
    print("this is decoded token claims", token.payload)
else:
    print("no token is provided in the header or the header is missing")
Run Code Online (Sandbox Code Playgroud)


Bac*_*ech 9

基本上任何 JWT 都是以下结果

  1. 有效载荷
  2. 秘密
  3. 编码算法

有效负载只是带有用户标识、角色、权限等的哈希图。

payload = {
  username: "James Bond",
  roles: ['admin'],
  permissions: ['user | add', 'user | edit'],
  id: 7,
}
Run Code Online (Sandbox Code Playgroud)

Secret是一个像密码一样的长字符串,您将其保存在 settings.py 中

SECRET_KEY = config('SECRET_KEY')
Run Code Online (Sandbox Code Playgroud)

编码算法是一种加密的方法

要解码,您必须使用 与编码相同的SECRET_KEY 。

import jwt
# Token generated by simple-jwt-django-rest-framework or any
token = "eyJ0eXAiOiJKV1QiL....";
    
print(jwt.decode(token, config('SECRET_KEY'), algorithms=["HS256"]))
Run Code Online (Sandbox Code Playgroud)

您可以将config('SECRET_KEY')替换为“123”或 settings.py 中的任何内容


Oha*_*Lad 4

我认为你应该发送 RAW_TOKEN 而不是 request._request

  if(verify_token_response.status_code == 200):
    jwt_object      = JWTAuthentication() 
    header          = jwt_object.get_header(request)
    raw_token       = jwt_object.get_raw_token(header)
    validated_token = jwt_object.get_validated_token(raw_token)
    user            = jwt_object.get_user(validated_token)
    print(user)
Run Code Online (Sandbox Code Playgroud)