安装的是rest_framework版本JWT,需要先安装RestFramework框架

pip install djangorestframework-simplejwt

在settings.py文件配置JWT

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}

在urls文件中配置路由信息:

from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
    TokenVerifyView
)

urlpatterns = [
    #token获取路由,访问这个路由可以获取token信息包含access和refresh,请求方式为post,需要携带username与password 这两个是固定参数
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),

    #刷新token,请求方式post需要携带refresh,返回数据会获得一个信息的access
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),

    #认证token,post请求,json形式传参{"token":access} token为固定参数名称
     path('token/verify/', TokenVerifyView.as_view(), name='token_verify'),
]

访问api/token获取到以下信息:
access:是token信息
refresh:是刷新令牌(就是token失效之后)使用这个令牌去获取新的token

{
    "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY2MDczOTIyOCwiaWF0IjoxNjYwNjUyODI4LCJqdGkiOiJjYzk4NmY0ZmNiOTQ0NTMxYmM3MWYxN2RkNzgzMTcyMSIsInVzZXJfaWQiOjEsIm5hbWUiOiJhZG1pbiJ9.oaH39XkMpocbHQeIL1wB-0S1knl5LuxJHsT4clTWA1E",
    "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjYwNjUzMTI4LCJpYXQiOjE2NjA2NTI4MjgsImp0aSI6ImIxNzE1OWVlZTU0NTRlMjg5ZjIyMmY3ZjMyNmVmZWI4IiwidXNlcl9pZCI6MSwibmFtZSI6ImFkbWluIn0.cYD0M0AYM3fmsMnPyE6WBYVqP-J25pGky1pULuvIXsU"
}

自定义令牌信息:
如果我们需要在以上返回的token信息中加入用户名称与ID可以自定义令牌:

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)

        # Add custom claims
        token['name'] = user.username

        return token

    # 自定义令牌信息
    def validate(self, attrs):
        data = super().validate(attrs)
        refresh = self.get_token(self.user)
        data['refresh'] = str(refresh) 
        data['access'] = str(refresh.access_token) 
        data['username'] = str(self.user.username) //用户名
        data['id'] = str(self.user.id) //用户id

        return data

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

然后还需将生成token的路由替换成我们自定义的类视图MyTokenObtainPairView

from .utils import MyTokenObtainPairView

urlpatterns = [

    path(r'api/token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
]

访问后得到的结果如下:

{
    "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY2MDczOTIyOCwiaWF0IjoxNjYwNjUyODI4LCJqdGkiOiJjYzk4NmY0ZmNiOTQ0NTMxYmM3MWYxN2RkNzgzMTcyMSIsInVzZXJfaWQiOjEsIm5hbWUiOiJhZG1pbiJ9.oaH39XkMpocbHQeIL1wB-0S1knl5LuxJHsT4clTWA1E",
    "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjYwNjUzMTI4LCJpYXQiOjE2NjA2NTI4MjgsImp0aSI6ImIxNzE1OWVlZTU0NTRlMjg5ZjIyMmY3ZjMyNmVmZWI4IiwidXNlcl9pZCI6MSwibmFtZSI6ImFkbWluIn0.cYD0M0AYM3fmsMnPyE6WBYVqP-J25pGky1pULuvIXsU",
    "username": "admin",
    "id": "1"
}

刷新Token,token失效后需要使用refresh令牌重新获取新的token值
配置路由地址:
使用POST方式请求,JSON形式携带{"token":refresh}请求之后可获得新的access

from rest_framework_simplejwt.views import TokenRefreshView

urlpatterns = [
    path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]

验证token
配置路由信息,同样以POST方式请求,JSON形式携带{"token":access},认证通过返回空数据状态码200,认证失败返回500状态,python控制台会输出:令牌失效或者错误的提示。

from rest_framework_simplejwt.views import TokenVerifyView

urlpatterns = [
    path('token/verify/', TokenVerifyView.as_view(), 
]

已注销
102 声望1 粉丝

没有人一生都是春天,更没有人一生都是冬天