安装
pip install djangorestframework-simplejwt
配置
setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework_simplejwt',
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
],
}
# 配置simplejwt
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': True,
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'AUTH_HEADER_TYPES': ('Bearer',),
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'TOKEN_TYPE_CLAIM': 'token_type',
# 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
# 'JTI_CLAIM': 'jti',
#
# 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
# 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
# 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
url.py
urlpatterns = [
path('admin/', admin.site.urls),
#版本号
# path('v1/', include('api.urls')),
# re_path(r'^(?P<version>[v1|v2]+)/',include('api.urls')),
re_path(r'^(?P<version>\w+)/', include('api.urls')),
# path('', include('api.urls')),
path('', include('hg.urls')),
re_path(r'^(?P<version>\w+)/', include('cx.urls')),
# 获取token
path('<slug:version>/obtaintoken/', token_obtain_pair, name='login'),
path('<slug:version>/refreshtoken/', token_refresh, name='refresh_token'),
path('<slug:version>/login/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('<slug:version>/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('<slug:version>/verify/', TokenVerifyView.as_view(), name='token_verify'),
]
验证使用
views.py
class MyView(APIView):
permission_classes = [permissions.IsAuthenticated, ]
def get(self,request,*args,**kwargs):
user = request.user
userInfo = {
'username': user.username,
'email': user.email,
'is_superuser': user.is_superuser,
}
return Response(userInfo)
0则评论给“simple_jwt”