1.pyjwt
安装
pip install pyjwt
生成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):
url = request.get_full_path()
list=['/sadmin/login/','/sadmin/reg/']
if url not in list:
token = request.META.get('HTTP_AUTHORIZATION')
if token:
s = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
newtoken = jwt.encode({'data':s},settings.SECRET_KEY,algorithm='HS256')
if token == newtoken:
return None
return HttpResponse(401)
return None
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);
});
|