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',
}

最新文章

  1. webform控件
  2. 顺序表java实现
  3. 横竖屏切换时候Activity的生命周期的总结
  4. [Perl] Getopt 函数来接收用户参数的使用
  5. 自动化 测试框架部署(python3+selenium2)
  6. 1430. Crime and Punishment(枚举)
  7. 1008. Image Encoding(bfs)
  8. Quartz1.8.5例子(八)
  9. Average(模拟)
  10. Android开发:怎样定制界面风格
  11. LeetCode - 728. Self Dividing Numbers
  12. 图解 CMS 垃圾回收机制原理,-阿里面试题
  13. English trip EM2-MP4 Teacher:Taylor voiceless consonant 清辅音 & voiced consonant 浊辅音
  14. Java Script--------问题错误解决意外的终止输入Uncaught SyntaxError: Unexpected end of input解决办法
  15. Mac 报错:-bash: telnet: command not found
  16. git入门(廖雪峰老师)
  17. [luogu2469] 星际竞速
  18. 交叉验证(Cross Validation)简介
  19. vue之计算属性和侦听器
  20. 1.5 C++ new和delete操作符

热门文章

  1. 201871010109-胡欢欢《面向对象程序设计(java)》第二周学习总结
  2. fiddler深入学习
  3. nginx 重定向 rewrite 规则
  4. 异常EXCEPTION_HIJACK(0xe0434f4e)
  5. ZBX_TCP_READ() time out windows
  6. 图的遍历 | 1076 bfs
  7. ML学习笔记(1)
  8. 深入js系列-环境
  9. E437: terminal capability "cm" required 解决办法
  10. libevent笔记2:Hello_World