JSON Web Token(JWT)是目前最流行的跨域身份验证解决方案。该token被设计为紧凑且安全的,特别适用于分布式站点的单点登陆(SSO)场景。JWT的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息,以便于从资源服务器获取资源,也可以增加一些额外的其它业务逻辑所必须的声明信息,该token也可直接被用于认证,也可被加密。
from django.shortcuts import render from django.views import View from django.http import HttpResponse, JsonResponse import json from utils.utils import get_token from apps.authority.models import User from rest_framework.views import APIView from rest_framework.response import Response
# users.py import re from apps.authority.models import User from django.contrib.auth.backends import ModelBackend from utils.constants import username_min, username_auth_max from utils.utils import verifyblank
defget_user_by_account(account): try: if account.isdigit(): # 用户名使用纯数字时判断手机号 if (len(account) == 11) and re.match(r'1[3456789]\d{9}', account): user = User.objects.get(mobile=account) else: user = None else: # 用户名不使用纯数字时判断用户名 if (username_min < len(account) < username_auth_max) and verifyblank(account): # 用户名检测长度和不能有空格 user = User.objects.get(username=account) else: user = None except User.DoesNotExist: user = None return user
classUsernameMobileAuthBackend(ModelBackend): defauthenticate(self, request, username=None, password=None, **kwargs): """自定义手机号和用户名认证""" # 登陆密码不能是纯数字 if password.isdigit(): returnNone user = get_user_by_account(username) if user isnotNoneand user.check_password(password): return user returnNone