关于后端:Django-40使用JWT

36次阅读

共计 2526 个字符,预计需要花费 7 分钟才能阅读完成。

装置的是 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"
}

查了很多文档都没有新版的用法,心愿对你有帮忙!

正文完
 0