前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >DRF利用JWT实现用户认证

DRF利用JWT实现用户认证

作者头像
SingYi
发布2022-07-13 20:07:02
4050
发布2022-07-13 20:07:02
举报
文章被收录于专栏:Lan小站Lan小站

根据上一篇文章可以知道JWT的原理和意义 所以在这里分享一下jwt在drf中的应用 auth.py 将jwt写出来

代码语言:javascript
复制
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中全局应用此认证方式

代码语言:javascript
复制
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": ['utils.auth.JwtAuthentication']
}

views.py 一个登录的view,将认证方式设为空,另外一个可以直接获取

代码语言:javascript
复制
# 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

www.lanol.cn
www.lanol.cn

验证Token成功

www.lanol.cn
www.lanol.cn

Token超时失效

www.lanol.cn
www.lanol.cn

这个auth.py不止在drf中可用,其他的web框架,fastapi啥的也是通用的,只要将返回改一下即可

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档