django使用JWT实现token身份验证

340 阅读1分钟

安装jwt软件包

pip3 install djangorestframework-simplejwt

查看安装的版本

pip3 list jwt

在setting.py里面进行配置

INSTALLED_APPS = [
'rest_framework_simplejwt',
]

添加登录认证配置

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}
# swagger页面认证界面采用
SWAGGER_SETTINGS = {
    'SECURITY_DEFINITIONS': {
        'api_key': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'token',
        }
    },
    'USE_SESSION_AUTH': False,
    'JSON_EDITOR': True,
}

打开urls.py文件配置

path('token-api/token/',TokenObtainPairView.as_view(),name='token_obtain_pair'),
path('token-api/token/refresh/',TokenRefreshView.as_view(),name='token_refresh'),
path('token-api/token/verify',TokenVerifyView.as_view(),name='token_verify'),

配置视图

from rest_framework_simplejwt import authentication
authentication_classes = (authentication.JWTAuthentication,)