测开平台(1) - 用户权限验证2-认证和授权

2019-11-10  本文已影响0人  足__迹

JWT

from django.urls import path, include
from rest_framework_jwt.views import obtain_jwt_token

urlpatterns = [

   path('login/', obtain_jwt_token),
]

2,在项目setting中设置
2.1 设置允许JWT认证

  'DEFAULT_AUTHENTICATION_CLASSES': [
      #默认首先token认证
      'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
      'rest_framework.authentication.SessionAuthentication',
      'rest_framework.authentication.BasicAuthentication'
  ],

2.2 设置路由

 path('user/',include('user.urls'))

演示:

注意使用POSTMAN 需要修改默认的JWT_AUTH_HEADER_PREFIX


image.png

源码:
这个函数负责token返回,如果需要定制则重写这个函数

def jwt_response_payload_handler(token, user=None, request=None):
    """
    Returns the response data for both the login and refresh views.
    Override to return a custom response such as including the
    serialized representation of the User.

    Example:

    def jwt_response_payload_handler(token, user=None, request=None):
        return {
            'token': token,
            'user': UserSerializer(user, context={'request': request}).data
        }

    """
    return {
        'token': token
    }

在utile中重写,在setting中重新指定:


image.png
  'JWT_RESPONSE_PAYLOAD_HANDLER': 'utils.jwt_handler.jwt_response_payload_handler',

JWT的组成

image.png
上一篇 下一篇

猜你喜欢

热点阅读