D26 我們介紹了 JWT token,接下來,我們要在 user login 成功後,回傳 jwt token 給 client 端
pip install djangorestframework-simplejwt
INSTALLED_APPS = [
...,
"rest_framework_simplejwt", # 加上這個
]
from datetime import timedelta
# 讓 access token 的時效只有 10 min
# refresh token 有 1 天
SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=10),
"REFRESH_TOKEN_LIFETIME": timedelta(days=1),
}
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
)
}
讓 login 的 respnose 改為 jwt token respones
from django.contrib.auth import authenticate
from django.http import JsonResponse
from rest_framework.decorators import api_view
from rest_framework_simplejwt.tokens import RefreshToken
@api_view(["GET"])
def hello_world(request):
return JsonResponse({"message": "Hello, World!"})
@api_view(["POST"])
def login_view(request):
account = request.data.get("account")
password = request.data.get("password")
user = authenticate(username=account, password=password)
if user is not None:
refresh = RefreshToken.for_user(user)
return JsonResponse({
"message": "Login successful!",
"access_token": str(refresh.access_token),
"refresh_token": str(refresh)
}, status=200)
else:
return JsonResponse({"message": "Invalid credentials."}, status=401)
啟動 server
python manage.py runserver
然後用 postman 打一下登入,現在的回應,就會是 jwt token 格式的 json