自定义中间件生成token
Posted 一只阿龙
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义中间件生成token相关的知识,希望对你有一定的参考价值。
Django 自定义生成中间件
生成jwt
class LoginAPIVIew(APIView):
# 登录
def post(self,request):
username = request.data.get('username')
password = request.data.get('password')
user = Admin_user.objects.filter(username=username).first()
if user and check_password(password,user.password):
token = jwt.encode({'data':{'userid':user.id,'username':user.username,'pic':user.pic}},settings.SECRET_KEY,algorithm='HS256')
return Response({'msg':'登录成功','code':200,'username':user.username,'pic':user.pic,'userid':user.id,'token':token,})
else:
return Response({'msg':'账号或密码错误'})
验证token
自定义中间件,新建一个token_middleware.py
class TokenMiddleware(MiddlewareMixin):
def process_request(self,request):
# 1.获取到url =request.get_full_path() http://localhsot:32r4/sadmin/test/
url = request.get_full_path()
# 2.定义一个白名单 list=['/sadmin/login','/sadmin/reg']
list=['/sadmin/login/','/sadmin/reg/']
# 3.判断 url not in list:
if url not in list:
# 4.获取token jwttoken 认证去认证
token = request.META.get('HTTP_AUTHORIZATION')
#4.1解析验证
if token:
#解决原来的token
s = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
#重新生成token
newtoken = jwt.encode({'data':s},settings.SECRET_KEY,algorithm='HS256')
if token == newtoken:
return None
return HttpResponse(401)
return None
# 4.通过return None
# 6.不能过 httpResponse('401')
Settings.py中配制
子应用名.文件名.类型
'sadmin.token_middeware.TokenMiddleware'
vue请求
var token = localStorage.getItem('token')
this.axios.get('sadmin/test/',{headers: { "Authorization": token }}).then(res=>{
if(res.data == 401){
alert('登录后访问')
}
})
拦截器
#interceptors main.js
axios.interceptors.request.use(
config => {
if(localStorage.getItem('token')){
config.headers['Authorization'] = localStorage.getItem('token');
}
return config;
},
error => {
return Promise.reject(error.response);
});
以上是关于自定义中间件生成token的主要内容,如果未能解决你的问题,请参考以下文章
System.IdentityModel.Tokens.JwtSecurityToken 自定义属性