Django 4.0使用JWT

安装的是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,
)

urlpatterns = [

    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]

访问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"
}

查了很多文档都没有新版的用法,希望对你有帮助!

你可能感兴趣的:(后端django)