繁体   English   中英

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

[英]How to decode and verify simple-jwt-django-rest-framework token

我正在尝试验证和解码 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'
            })

此代码适用于我的令牌验证。 它正在正确验证令牌,但是当我检索 valied_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"
        }
    ]
}

我认为您应该发送 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)

基本上任何 JWT 都是由于

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

有效载荷只是 hashmap 具有用户标识、角色、权限等。

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

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

当您配置rest_framework_simplejwt身份验证时,您是否必须在文件settings.py上配置SIMPLE_JWT变量,并且有ALGORITHMSIGNING_KEY如何:

SIMPLE_JWT = {
    ...

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

其中SIGNING_KEYsettings.py文件中的SECRET_KEY常量。 然后,您是否可以在SIMPLE_JWT dict 的ALGORITHM键中获取算法值。 就我而言,算法是'HS512'

知道算法后,您是否必须从settings.py导入SIMPLE_JWT并且可以使用jwt中的decode方法,示例如下:

import jwt
from your_project.settings import SIMPLE_JWT

...

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

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

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

暂无
暂无

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

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