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

9

我正在尝试验证和解码simple-jwt-django-rest-framework token。我知道可以使用simple-jwt的verify 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'
            })

这段代码用于验证令牌,它能够正确地验证令牌,但当我尝试检索已验证的令牌和用户时,它会出现错误:
{
    "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"
        }
    ]
}

这个答案将有助于您解码令牌并验证用户 - Madhura Prasanna
4个回答

12
你可以使用 rest_framework_simplejwt.authentication 模块中的 JWTAuthentication 类。它包含一个名为 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")

这正是我所需要的,谢谢。我需要验证请求的用户身份。 - Yang

8

基本上任何JWT都是由以下组成:

  1. 负载
  2. 密钥
  3. 编码算法

负载只是一个包含用户标识、角色、权限等信息的哈希表。

payload = {
  username: "James Bond",
  roles: ['admin'],
  permissions: ['user | add', 'user | edit'],
  id: 7,
}

Secret是一个长字符串,类似于密码,你可以在setting.py中设置它。

SECRET_KEY = config('SECRET_KEY')

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

要进行解码,必须使用相同的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"]))

你可以使用settings.py文件中的"123"或其他值替换config('SECRET_KEY')。

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)

正是我所需的。 - Atif Shafi

2

当您配置rest_framework_simplejwt身份验证时,是否需要在settings.py文件中配置SIMPLE_JWT变量,其中包括ALGORITHMSIGNING_KEY如何设置:

SIMPLE_JWT = {
    ...

    'ALGORITHM': 'HS512',
    'SIGNING_KEY': SECRET_KEY,
    ...
}

在您的settings.py文件中,SIGNING_KEYSECRET_KEY常量。然后,您可以在SIMPLE_JWT字典中的ALGORITHM键中获取算法值。在我的情况下,算法为'HS512'

了解算法后,您需要从settings.py导入SIMPLE_JWT,然后可以使用以下示例中的jwtdecode方法:

import jwt
from your_project.settings import SIMPLE_JWT

...

token = "eyJ0eXAiOiJKV1QiLC..."
jwt.decode(
   token,
   SIMPLE_JWT['SIGNING_KEY'],
   algorithms=[SIMPLE_JWT['ALGORITHM']],
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接