1. 安装jwt库
pip install PyJWT
  1. 在Django的settings.py文件中添加JWT相关配置
# JWT配置
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=4),  # token有效期
    'JWT_ALLOW_REFRESH': True,  # 是否允许刷新token
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),  # 刷新token有效期
    'JWT_AUTH_HEADER_PREFIX': 'JWT',  # token前缀
}
  1. 在视图中添加验证token的装饰器
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token

# 登录获取token
urlpatterns = [
    url(r'^api-token-auth/', obtain_jwt_token),
]

# 刷新token
urlpatterns += [
    url(r'^api-token-refresh/', refresh_jwt_token),
]

# 其他接口
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated

@api_view(['GET'])
@authentication_classes((JSONWebTokenAuthentication,))
@permission_classes((IsAuthenticated,))
def my_view(request):
    # 在这里写具体的业务逻辑
    return Response({'msg': '验证成功'})

在其他接口中,只需要在@api_view装饰器中添加@authentication_classes((JSONWebTokenAuthentication,))和@permission_classes((IsAuthenticated,))即可实现token验证。其中,JSONWebTokenAuthentication是jwt提供的验证类,IsAuthenticated是DRF提供的验证类,用于验证用户是否已经通过认证。

需要注意的是,如果使用了JWT_EXPIRATION_DELTA配置项设置token的有效期,那么在4小时内访问接口,token不会过期,但是在4小时之后,即使用户一直在操作,token也会过期。如果需要实现用户4小时内一直操作token不过期的功能,可以考虑在每次用户访问接口时,更新token的过期时间。可以通过自定义jwt的payload来实现这一功能。具体实现可以参考官方文档

django 实现jwt接口验证token过期时间为4小时4小时未操作则token过期4小时内操作则无token过期配置jwt 每个接口验证方法?

原文地址: https://www.cveoy.top/t/topic/hscJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录