settings.py中配置
python
####################################JWT KEY##################################
JWT_KEY = '%*5xpP%2xL'
####################################################################
utils.py中引用
python
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
视图函数中
python
user_profile = UserProfile.objects.get(username=username)
payload = {
'id': user_profile.pk,
'username': username
}
token = encode_jwt(payload)
验证时
python
jwt_decode_result = decode_jwt(request.headers.get('authorization'))
if not jwt_decode_result:
context = {
'code': 30007,
'error': '获取的地址用户并非当前用户。'
}
return JsonResponse(context)