栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Django DRF框架相关内容

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Django DRF框架相关内容

JWT 认证

JWT 认证可以解决 HTTP 无状态认证及跨域登录的问题,常见于不同域名网页使用同一账户登录的解决方案当中,在 Django 中可以使用 JWT 代替 Session 进行认证。Session 一般保存于服务器的数据库中,而 JWT 通过 Token 的形式,将认证结果保存在 cookie 中,二者在保存上存在区别

实现
  • pyjwt 2.4.0

实现代码如下:

class JWTAuth(View):
    """create token and decode token"""
    def post(self, request, *args, **kwargs):
        username = request.POST.get('username')
        password = request.POST.get('password')
        # check username and password
        user = authenticate(request, username=username, password=password)
        if user is not None and user.is_active:
            # use get_jwt_token to create a token
            jwt_token = self.get_jwt_token(username)
            return JsonResponse({"jwt_toke":jwt_token})
        return JsonResponse({"message":"check name and password"})
    
    def get(self, request):
        headers = request.headers
		# check jwttoken in headers or not
        if 'jwttoken' in headers:
            # decode token
            if self.decode_jwt_token(headers['jwttoken']):
                return JsonResponse({"message":"This is Auth page!"})
            else:
                return JsonResponse({"error":"You get a wrong token"})
        else:
            return JsonResponse({"error":"You dont have token"})
        return JsonResponse({"message":"this is token page!"})
    
    @staticmethod
    def get_jwt_token(username):
        """crete jwt token"""
        payload={
            # Set the expiration time for example 3600 seconds
            'exp':datetime.datetime.utcnow() + datetime.timedelta(3600),
            'iat':datetime.datetime.utcnow(),
            'data':{'username':username},
        }
        # payload:payload
        # string:salt
        # algorthm:encryption method
        encode_jwt = jwt.encode(payload, "jfjufcb37%jfjoeo", algorithm='HS256')
        return encode_jwt
    
    @staticmethod
    def decode_jwt_token(encode_jwt):
        """decode jwt """
        result = jwt.decode(encode_jwt,"jfjufcb37%jfjoeo", algorithms=['HS256'])
        return result
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1026681.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号