Django JWT配置使用
settings.py中配置
####################################JWT KEY##################################
JWT_KEY = '%*5xpP%2xL'
####################################################################
utils.py中引用
import jwt
from django.conf import settings
def encode_jwt(payload):
string = jwt.encode(payload=payload, key=settings.JWT_KEY)
return string
def decode_jwt(jwt_string):
try:
payload = jwt.decode(jwt=jwt_string, key=settings.JWT_KEY, algorithms='HS256')
return payload
except Exception as e:
return False
视图函数中
user_profile = UserProfile.objects.get(username=username)
payload = {
'id': user_profile.pk,
'username': username
}
token = encode_jwt(payload)
验证时
jwt_decode_result = decode_jwt(request.headers.get('authorization'))
if not jwt_decode_result:
context = {
'code': 30007,
'error': '获取的地址用户并非当前用户。'
}
return JsonResponse(context)
原文地址:https://blog.csdn.net/weixin_52505665/article/details/142958266
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!