1.認證與授權
1.驗證:身份驗證是驗證個人或設備標識的過程。身份驗證過程之一是登錄過程。注冊網站后,您的信息(ID,密碼,名稱,電子郵件等)將存儲在其數據庫中。之后,您無需創(chuàng)建帳戶即可提供信息。相反,您只需要提供用戶名和密碼來驗證您的身份,網站就會自動知道您正在訪問。
2.授權:授權是用于確定用戶特權或訪問級別的安全機制。在許多社區(qū)網站上,只有上傳帖子和管理員的人才能刪除它。當其他人嘗試刪除帖子時,網站應該拋出錯誤(但是在許多情況下,他們甚至看不到刪除按鈕)。因此,對于每個請求,用戶都需要證明自己具有權限。
2.什么是JWT
JSON Web令牌(JWT)是一種開放標準(RFC 7519),它定義了一種緊湊且自包含的方式,用于在各方之間安全地將信息作為JSON對象進行傳輸。您可以使用JWT對請求進行身份驗證和授權。
JWT由三個串聯的Base64url編碼的字符串(標頭,有效負載和簽名)組成,并用點號(,)分隔。標頭包含有關令牌和加密算法類型的元數據。簽名用于驗證令牌的可信度。有效負載包含用于身份驗證和授權的所有必要數據。
3.存儲JWT
當用戶登錄時,服務器將創(chuàng)建JWT并將其發(fā)送到客戶端。然后,客戶端將其存儲到會話存儲或本地存儲。每次客戶端向服務器端發(fā)送需要身份驗證或授權的請求時,都會在授權標頭上發(fā)送JWT。易受XSS(跨站點腳本)攻擊:會話和本地存儲可通過JavaScript訪問。惡意第三方可以將其JS注入網站,從而可以向API發(fā)出請求。
服務器將JWT存儲在Cookie中,并使用存儲在Cookie中的JWT驗證用戶。Cookies容易受到CSRF的攻擊,因為它們隨每個請求一起發(fā)送。因此,惡意的第三方可以輕松地提出意想不到的請求。
4.Django中的JWT
# 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中發(fā)送令牌
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
到此這篇關于Django中的JWT身份驗證的實現的文章就介紹到這了,更多相關Django JWT身份驗證內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- django drf框架中的user驗證以及JWT拓展的介紹
- 微信小程序登錄對接Django后端實現JWT方式驗證登錄詳解