# js <script type="text/javascript" src="{% static 'js/jquery.cookie.js' %}"></script> $(function() { $('.fa-upload').on('click', function() { $('p').css("display","block"); var file = $("#pemkey")[0].files[0]; var dict = new FormData(); dict.append('file', file); $.ajax({ type:"POST", url:"/B/middle/index/key/", data: dict, processData: false, // jQuery不要去处理发送的数据 contentType: false, // jQuery不要去设置Content-Type请求头 success:function(result){ if(result.status=="success") { var jwt = result.jwt; var jwtv = $.cookie('jwt'); console.log(jwt) console.log(jwtv) // $.removeCookie('jwt'); $.cookie('jwt', jwt, { expires: 1, path: '/' }); window.location.href = "/B/home/" } else { $('p').css("display","block"); $('p').html("请上传正确的文件"); } } }); }); });
#utils.py def load_jwt(user): rdmstr="" for i in range(11): rdmstr+=random.choice('abcdefghijklmnopqrstuvwxyz!@#$%^&*()') token = jwt.encode({ 'exp': datetime.utcnow() + timedelta(minutes=30), #过期时间 'iat': datetime.utcnow(), #发布时间 'data': { 'user': user, 'random':rdmstr } }, settings.SECRET_KEY, algorithm='HS256') return token.decode("utf-8") def check_jwt(token): if token == None: return False token = token.encode('utf-8') try: data = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) except: return False time_m = time.localtime(data["exp"]) t_time = time.strftime("%Y--%m--%d %H:%M:%S", time_m) ntime_m = time.localtime(time.time()) nt_time = time.strftime("%Y--%m--%d %H:%M:%S", ntime_m) if t_time < nt_time: return False else: return data
# views.py jwt = utils.load_jwt(mykey)
# Authentication.py import os class MyAuthenticate_base(BaseAuthentication): def authenticate(self, request): if "jwt" not in request.COOKIES: raise exceptions.AuthenticationFailed('用户认证失败') myjwt = request.COOKIES["jwt"] yon = utils.check_jwt(myjwt) if yon == False: raise exceptions.AuthenticationFailed('用户认证失败') else: mykey = yon["data"]["user"] token_obj = UserKey.objects.filter(UserId=mykey).first() if not token_obj: raise exceptions.AuthenticationFailed('用户认证失败') return (token_obj, token_obj) def authenticate_header(self, request): pass
Django-restframework 常用记录(JWT,权限)
最新推荐文章于 2022-08-22 14:38:09 发布