【问题标题】:How to decode and verify simple-jwt-django-rest-framework token如何解码和验证 simple-jwt-django-rest-framework 令牌
【发布时间】:2020-11-02 17:19:17
【问题描述】:

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

【问题讨论】:

标签: python django-rest-framework django-views django-rest-framework-simplejwt


【解决方案1】:

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

【讨论】:

  • 正是我需要的
【解决方案2】:

基本上任何 JWT 都是

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

Payload只是带有用户标识、角色、权限等的hashmap。

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

Secret 是一个类似于密码的长字符串,您的设置中有它。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 中的任何内容

【讨论】:

    【解决方案3】:

    您可以使用来自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")
    

    【讨论】:

      【解决方案4】:

      配置rest_framework_simplejwt认证的时候,是不是一定要在文件settings.py上配置SIMPLE_JWT变量,还有ALGORITHMSIGNING_KEY怎么这样:

      SIMPLE_JWT = {
          ...
      
          'ALGORITHM': 'HS512',
          'SIGNING_KEY': SECRET_KEY,
          ...
      }
      

      SIGNING_KEY 是您的 settings.py 文件中的 SECRET_KEYconstant。 那么,是否可以在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']],
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-22
        • 2020-09-12
        • 2019-08-01
        • 2019-04-22
        • 2019-02-27
        • 2019-06-20
        • 2019-01-01
        • 2013-09-11
        相关资源
        最近更新 更多