技术分享1 分钟阅读
django实现jwt鉴权
JWT
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from apitest.tool import jwt_token
from apitest.tool.response import ResponseDict
class JwtTokenAuthentication(BaseAuthentication):
def authenticate_header(self, request):
pass
def authenticate(self, request):
# 实例化我们的自定义响应体类
res = ResponseDict()
# 获取用户请求头中携带的token
authorization = request.META.get('HTTP_AUTHORIZATION', '')
# 判断是否携带token
if not authorization:
res.msg = '未获取到Authorization请求头'
res.code = 1001
raise AuthenticationFailed(res.dict)
# 验证用户携带的token
result = jwt_token.validate_token(authorization)
# 判断token是否有效,无效输出错误提示
if not result['status']:
res.msg = result['error']
res.code = 1001
raise AuthenticationFailed(res.dict)
# token有效,返回用户字典和token
return (result, authorization)
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'apitest.tool.authentications.JwtTokenAuthentication',
]}
import datetime
import jwt
from jwt import exceptions
salt = 'iv%x1fo9l7_u9bfs_u!9#g#m*)*=esssssj@bek5)ss(@u3kh*7d2+unjv='
def generate_token(playload, timeout = 120):
'''
生成token
:param playload: 一般为用户id、用户名的字典
:param timeout: 多久过期,单位:分钟
:return:
'''
# 构造header
headers = {
'typ': 'jwt',
'alg': 'HS256'
}
# 构造payload
playload = playload
# token有效期,我这边设置为了分钟,即x分钟后过期
playload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(days=1)
# 构造signature即token
token = jwt.encode(payload=playload, key=salt, algorithm="HS256", headers=headers)
# return str(token,encoding='utf-8')
return str(token)
def validate_token(token):
'''校验token有效性'''
# 定义返回相应字典
result = {'status': False, 'data': None, 'error': None}
try:
# 从token中获取payload【不校验合法性】
# unverified_payload = jwt.decode(token, None, False)
# print(unverified_payload)
# 从token中获取payload【校验合法性】;如果token正确,返回生成token时的playload字典
token = token.split()
if token[0] == 'Bearer':
verified_payload = jwt.decode(token[1], salt,algorithms="HS256" )
result['status'] = True
result['data'] = verified_payload
else:
result['error'] = ' token错误'
except exceptions.ExpiredSignatureError:
result['error'] = 'token已失效'
except jwt.DecodeError as err:
result['error'] = 'token认证失败'
except jwt.InvalidTokenError:
result['error'] = '非法的token'
print(result)
return result
局部视图不使用token校验
from rest_framework.views import APIView
class ExampleView(APIView):
authentication_classes = []
def get(self, request, format=None):
# do something
某一个接口不鉴权
class ExampleView(APIView):
authentication_classes = [BasicAuthentication]
def get(self, request, format=None):
self.authentication_classes = []
# do something
有关使用上的问题,欢迎您在底部评论区留言,一起交流~
读者评论
评论会同步写入该文在 Notion 中的页面底部(与正文同页,便于管理)。
暂无评论,欢迎抢沙发。