根据上一篇文章可以知道JWT的原理和意义
所以在这里分享一下jwt在drf中的应用
auth.py
将jwt写出来
import datetime
import jwt
from django.conf import settings
from jwt import exceptions
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
def create_token(payload, exp=30):
headers = {'typ': 'jwt', 'alg': 'HS256'}
payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(days=exp)
return jwt.encode(payload, settings.SECRET_KEY, "HS256", headers)
class JwtAuthentication(BaseAuthentication):
def authenticate(self, request):
# 获取请求头中Token
token = request.META.get('HTTP_TOKEN')
try:
payload = jwt.decode(token, settings.SECRET_KEY, "HS256")
except exceptions.ExpiredSignatureError:
raise AuthenticationFailed({'code': 204, 'msg': 'Token已失效'})
except jwt.DecodeError:
raise AuthenticationFailed({'code': 204, 'msg': 'Token认证失败'})
except jwt.InvalidTokenError:
raise AuthenticationFailed({'code': 204, 'msg': 'Token非法'})
return payload, token
settings.py
在drf的view中全局应用此认证方式
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": ['utils.auth.JwtAuthentication']
}
views.py
一个登录的view,将认证方式设为空,另外一个可以直接获取
# Create your views here.
from rest_framework.views import APIView
from utils.auth import create_token
from utils.commen import standard_response
class LoginView(APIView):
authentication_classes = []
@staticmethod
def post(request, *args, **kwargs):
username = request.data.get('username')
password = request.data.get('password')
if not username == 'lan' and password == 'password':
return standard_response(None, msg='用户名或密码错误')
token = create_token({'username': username})
return standard_response(data=token, msg='登陆成功')
class IndexView(APIView):
@staticmethod
def post(request, *args, **kwargs):
return standard_response(data='来源网站:www.lanol.cn', msg=f'欢迎您{request.user["username"]}')
登录获取Token
验证Token成功
Token超时失效
这个auth.py不止在drf中可用,其他的web框架,fastapi啥的也是通用的,只要将返回改一下即可
牛哇 没点基础看不懂
阿斯顿
aa
aa