jwt认证生成后的token后端解析
一.首先前端发送token
token所在的位置headers
{\'authorization\':token的值\',Content-Type\':application/json}
在ajax写
//只展示headers部分代码
headers:{"authorization":this.$cookies.get("token")}
//token值一般是放在cookies里面
//ajax提交默认就是json格式所有不需要声明js格式
二.后端接受并解析token
1.首先先定义个认证类
from rest_framework.exceptions import AuthenticationFailed
import jwt
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
from rest_framework_jwt.authentication import jwt_decode_handler
from rest_framework_jwt.authentication import get_authorization_header
class JWTAuthentication(BaseJSONWebTokenAuthentication):
# 自定义认证类,重写authenticate方法
def authenticate(self, request):
# 认证通过,返回user,auth
# 认证失败,返回None
# auth = request.META.get(\'HTTP_AUTHORIZATION\') # 前台用auth携带token
# 通过前台传过来的请求头中获取auth
auth = get_authorization_header(request)
if not auth:
raise AuthenticationFailed(\'Authorization 字段是必须的\')
try:
payload = jwt_decode_handler(auth)
# 出现jwt解析异常,直接抛出异常,代表非法用户,也可以返回None,作为游客处理
except jwt.ExpiredSignature:
raise AuthenticationFailed(\'token已过期\')
except:
raise AuthenticationFailed(\'token非法\')
user = self.authenticate_credentials(payload)
return (user, auth)
关于其中的几个方法
- auth = request.META.get(\'HTTP_AUTHORIZATION\') 获取token的
字符串格式 - auth = get_authorization_header(reuqest对象) 获取token的
二进制格式 - jwt_decode_handler(token的
二进制格式)- 如果token没有过期:返回用户信息
- 如果token过期:
抛异常,过期的异常是jwt.ExpiredSignature
- authenticate_credentials(jwt_decode_handler解析后信息)返回user对象
2.局部调用用户认证类
#评率认证类写法
from rest_framework.throttling import SimpleRateThrottle
class SMSRateThrottle(SimpleRateThrottle):
scope = \'sms\' #这个是为了全局设置给予的一个变量名称
# 只对提交手机号的get方法进行限制
def get_cache_key(self, request, view):
mobile = request.query_params.get(\'mobile\')
# 没有手机号,就不做频率限制
if not mobile:
return None
# 返回可以根据手机号动态变化,且不易重复的字符串,作为操作缓存的key
return \'throttle_%(scope)s_%(ident)s\' % {\'scope\': self.scope, \'ident\': mobile}
class Test(APIView):
authentication_classes = [我们自定义用户认证的类] #如[JWTAuthentication]
#来判断登入账号的信息算游客还是正常用户
permission_classes =[IsAuthenticated]
#给与权限
#AllowAny:允许所有
#IsAuthenticated:只允许登入用户
#IsAuthenticatedOrReadOnly:游客只读,登录用户无限制
#IsAdminUser:是否是后台用户
DEFAULT_THROTTLE_RATES = [频率认证类]#如[SMSRateThrottle]
#局部评率认证
#满足以上给予的权限才可以进行下面的操作
3.全局调用用户认证类
setting.py中
#drf配置
"""
AllowAny:允许所有用户
IsAuthenticated:只允许登录用户
IsAuthenticatedOrReadOnly:游客只读,登录用户无限制
IsAdminUser:是否是后台用户
"""
REST_FRAMEWORK = {
\'DEFAULT_AUTHENTICATION_CLASSES\': [
# django默认session校验:校验规则 游客 及 登录用户
# \'rest_framework.authentication.SessionAuthentication\',
# \'rest_framework.authentication.BasicAuthentication\',
# \'rest_framework_jwt.authentication.JSONWebTokenAuthentication\',
\'api.authentications.JWTAuthentication\',
],
\'DEFAULT_PERMISSION_CLASSES\': [
# \'rest_framework.permissions.AllowAny\',
# 全局配置:一站式网站(所有操作都需要登录后才能访问)
# \'rest_framework.permissions.IsAuthenticated\',
],
\'DEFAULT_THROTTLE_RATES\': {
\'user\': \'5/min\', # 登录的用户一分钟可以访问5次
\'anon\': \'3/min\', # 游客一分钟可以访问3次
\'sms\': \'1/min\' #同一个手机1分钟一次
}
}
jwt配置
import datetime
JWT_AUTH = {
\'JWT_EXPIRATION_DELTA\': datetime.timedelta(seconds=1000), #生成token有效期
\'JWT_AUTH_HEADER_PREFIX\': \'TOKEN\',
}