Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

Gray-Ice

个人博客兼个人网站

首先,安装pyjwt模块:

1
pip3 install pyjwt

然后写出装饰器函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# jwt验证
def jwt_isvalid(func):
def inner(request, *args, **kwargs):
# 获取token
token = request.GET.get('token', None)
# 如果获取到了token
if token:
try:
# 进行解密,如果token过期则返回登录过期
jwt_decode = jwt.decode(token, 'grayice777', algorithms=['HS256'])
# 成功解密后将解密的结果加入到request.META中以传递给被装饰函数,被装饰函数只需执行jwt_token = request.META['jwt_token']即可取得解密内容
request.META['jwt_token'] = jwt_decode

func(request, *args, **kwargs)
# token过期,捕获异常,返回响应
except jwt.exceptions.ExpiredSignatureError:
return Response({'code': 403, 'msg': '您的登录已过期'})

# 没有获取到token,返回响应
else:
return Response({'code': 403, 'msg': '您的登录已过期'})

return inner

被装饰函数:

1
2
3
4
5
6
from django.utils.decorators import method_decorator
class GETSelfInformation(APIView):
@method_decorator(jwt_isvalid)
def get(self, request):
print(request.META['jwt_token'])
return Response({'code': 200, 'msg': 'Fine'})

评论



愿火焰指引你