jwt的快速使用

jwt的使用步骤

 

第一步:安装模块

pip install djangorestframework-simplejwt

 

第二步:注册app

# settings文件配置
INSTALLED_APPS = [
    ...
    'rest_framework_simplejwt',
    ...
]

 

第三步:settings文件配置

import datetime
SIMPLE_JWT = {
    # token有效时长
    'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=30),
    # token刷新后的有效时间
    'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=1),
}

 双token认证的介绍

 

第四步:迁移数据库、创建超级用户

makemigrations
migrate
createsuperuser

 

第五步:路由层配置

from rest_framework_simplejwt.views import token_obtain_pair, token_verify, token_refresh

urlpatterns = [
    path('login/', token_obtain_pair),
    path('verify/', token_verify),
    path('refresh/', token_refresh),
]

 

第六步:配置接口

配置方法一:

视图层配置:需要导入两个模块

from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.permissions import IsAuthenticated

 

class BookView(APIView):
    # 局部加:认证类--->带来认证信息,会校验,不带认证信息,不管,需要配合一个权限类使用
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]  # 权限类,没登录的用户没权限

    def get(self, request):
        return Response("")

 

配置方法二:

不在视图层加权限和认证类,改为全局配置

settings层配置:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

 

 

第七步:测试接口

 

posted @ 2024-01-03 20:35  wellplayed  阅读(9)  评论(1编辑  收藏  举报