JWT登录
from django.urls import path
from user import views
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
path('login/', obtain_jwt_token),
]
# JWT登录
def Login_return(token, user=None, request=None, role=None):
'''
:param token: jwt 生成的token值
:param user: User对象
:param request: 请求
:return:
'''
if user.first_name:
name = user.first_name
else:
name = user.username
return {
'authenticated': 'true',
'id': user.id,
'role': role,
'name': name,
'username': user.username,
'email': user.email,
'token': token,
}
# jwt载荷中的有效期设置
JWT_AUTH = {
# 1. token前缀:headers中 Authorization 值的前缀
'JWT_AUTH_HEADER_PREFIX' : 'JWT',
# 2. token有效期:一天有效
'JWT_EXPIRATION_DELTA' : datetime.timedelta(days=1),
# 3. 刷新token:允许使用旧的token换新token
'JWT_ALLOW_REFRESH': True,
# 4. token有效期:token在24小时内过期,可续期token
'JWT_REFRESH_EXPIRATION_DELTA':datetime.timedelta(hours=24),
# 5. 自定义JWT载荷信息:自定义返回格式,需要手工创建
'JWT_RESPONSE_PAYLOAD_HANDLER' : 'user.views.Login_return',
}
多方式登录
from django.urls import path
from user import views
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
path('login/', obtain_jwt_token),
]
# 多方式登录
class JJAuth(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
try:
user = User.objects.get(Q(username=username) | Q(phone=username) | Q(email=username))
except Exception as e:
return None
if user is not None and user.check_password(password):
return user
# 自定义验证后端
AUTHENTICATION_BACKENDS = ['user.views.JJAuth']