Django中JWT身份验证过程是什么,有哪些要点
Admin 2022-07-08 群英技术资讯 467 次浏览
1.验证:身份验证是验证个人或设备标识的过程。身份验证过程之一是登录过程。注册网站后,您的信息(ID,密码,名称,电子邮件等)将存储在其数据库中。之后,您无需创建帐户即可提供信息。相反,您只需要提供用户名和密码来验证您的身份,网站就会自动知道您正在访问。
2.授权:授权是用于确定用户特权或访问级别的安全机制。在许多社区网站上,只有上传帖子和管理员的人才能删除它。当其他人尝试删除帖子时,网站应该抛出错误(但是在许多情况下,他们甚至看不到删除按钮)。因此,对于每个请求,用户都需要证明自己具有权限。
JSON Web令牌(JWT)是一种开放标准(RFC 7519),它定义了一种紧凑且自包含的方式,用于在各方之间安全地将信息作为JSON对象进行传输。您可以使用JWT对请求进行身份验证和授权。
JWT由三个串联的Base64url编码的字符串(标头,有效负载和签名)组成,并用点号(,)分隔。标头包含有关令牌和加密算法类型的元数据。签名用于验证令牌的可信度。有效负载包含用于身份验证和授权的所有必要数据。
当用户登录时,服务器将创建JWT并将其发送到客户端。然后,客户端将其存储到会话存储或本地存储。每次客户端向服务器端发送需要身份验证或授权的请求时,都会在授权标头上发送JWT。易受XSS(跨站点脚本)攻击:会话和本地存储可通过JavaScript访问。恶意第三方可以将其JS注入网站,从而可以向API发出请求。
服务器将JWT存储在Cookie中,并使用存储在Cookie中的JWT验证用户。Cookies容易受到CSRF的攻击,因为它们随每个请求一起发送。因此,恶意的第三方可以轻松地提出意想不到的请求。
# settings.py SECRET_KEY = 'abcde1234', JWT_ALGORITHM = 'HS256'
# user/views.py import json from datetime import datetime, timdelta from django.conf import settings from django.http import JsonResponse from django.views import View import bcrypt import jwt from .models import User from token_utils import user_token class UserSignInView(View): def post(self, request): try: data = json.loads(request.body) username = data['username'] pw_input = data['password'] user = User.objects.filter(username=username).first() if user is None: return JsonResponse({"message": "INVALID_USERNAME"}, status=401) if bcrypt.checkpw(pw_input.encode('utf-8'), user.password.encode('utf-8')): key = settings.SECRET_KEY algorithm = settings.JWT_ALGORITHM token = jwt.encode( { 'iss': 'me', 'id': user.id, 'exp': datetime.utcnow() + timedelta(days=14) }, key, algorithm=algorithm).decode('utf-8') response = JsonResponse( { 'message': 'SUCCESS' }, status=200 ) # 当使用本地/会话存储而不是Cookie时,只需在JsonResponse中发送令牌 if data.get('remember_me') is not None: max_age = 14*24*60*60 # 14 days expires = datetime.strftime( datetime.utcnow() + timedelta(seconds=max_age), "%Y-%m-%d %H:%M:%S" ) response.set_cookie( 'token', token, max_age=max_age, expires=expires, httponly=True ) return response return JsonResponse({"message": "WRONG_PASSWORD"}, status=401) except KeyError as e: return JsonResponse({'message': f'KEY_ERROR: {e}'}, status=400) except ValueError as e: return JsonResponse({'message': f'VALUE_ERROR: {e}'}, status=400)
# token_utils.py import json from django.conf import settings from django.http import JsonResponse import jwt from user.models import User def user_token(func): def wrapper(self, request, *args, **kwargs): try: token = request.COOKIES.get('token') # token = request.headers.get('token') key = settings.SECRET_KEY algorithm = settings.JWT_ALGORITHM if token is None: return JsonResponse({"message": "INVALID_TOKEN"}, status=401) decode = jwt.decode(token, key, algorithm=algorithm) request.user = User.objects.get(id=decode['id']) except jwt.ExpiredSignatureError: return JsonResponse({"message": "EXPIRED_TOKEN"}, status=400) return func(self, request, *args, **kwargs) return wrapper
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要和大家分享几个Python Pandas中处理CSV文件的常用技巧,如:统计列值出现的次数、筛选特定列值、遍历数据行等,需要的可以参考一下
如何计算python代码耗时是多少?一些Python新手不太清楚要怎样统计python代码耗时,文本就给大家介绍几种方法,时间戳相减、装饰器、timeit模块、重复调用 timeit()和cProfile性能分析工具。下面我们一起来具体看看吧。
这篇文章主要为大家介绍了Python上下文管理器,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助<BR>
flask是python web开发的常用框架之一。本文将讲述flask如何实现修改密码和免密登录功能
这篇文章主要介绍了Python中的列表条件求和方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008