在你的意见.py
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from decouple import config
from django.contrib.auth import authenticate
import jwt
@api_view(['POST'])
@permission_classes([AllowAny])
def get_tokens_for_user(request):
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username=username, password=password);
if user is not None:
refreshToken = RefreshToken.for_user(user)
accessToken = refreshToken.access_token
decodeJTW = jwt.decode(str(accessToken), config('SECRET_KEY'), algorithms=["HS256"]);
# add payload here!!
decodeJTW['iat'] = '1590917498'
decodeJTW['user'] = 'tiago'
decodeJTW['date'] = '2020-05-31'
#encode
encoded = jwt.encode(decodeJTW, config('SECRET_KEY'), algorithm="HS256")
return Response({
'status': True,
'refresh': str(refreshToken),
'access': str(encoded),
})
else:
return Response({
'status': False
})
# No backend authenticated the credentials
在你的 urls.py
from django.urls import path, include
from .views import get_tokens_for_user
urlpatterns = [
path('login/', get_tokens_for_user, name="login"),
]
在你的 settings.py
from pathlib import Path
from datetime import timedelta
from decouple import config
...
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# Application definition
INSTALLED_APPS = [
...
# Rest
'rest_framework',
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
# JWT
# https://django-rest-framework-simplejwt.readthedocs.io/en/latest/settings.html
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'AUTH_HEADER_TYPES': ('Bearer',),
'SIGNING_KEY': config('SECRET_KEY'),
'VERIFYING_KEY': config('SECRET_KEY'),
'ALGORITHM': 'HS256',
}
在您的根目录中添加 .env
SECRET_KEY = 'ep@4ojr4m!h73y2j(stackoverflow)kra1*@tq$5el626wf@&p60)7u!6552+-'
运行时值
decodeJTW = {
'token_type': 'access',
'exp': 1612651527,
'jti': '7f415b28610348468ce74ec0f480fad1',
'user_id': 2,
'iat': '1590917498',
'user': 'tiago',
'date': '2020-05-31'
}
encode = {
"status":true,
"refresh":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYxMjczNDU0NywianRpIjoiMDQ0MDI3ZTQzMTc2NDFiNDhhOGI2MjU4MjE4ZGZjNDkiLCJ1c2VyX2lkIjoyfQ.Qf0YfJLAmdYuavDHVng7Bwjmka551G6c1Gi4e-UdRuc",
"access":"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjEyNjUxNzQ3LCJqdGkiOiI2OWEzNjYwYjYxMTk0MzVjYjljZTA0OGQ3MmE1ODk1YSIsInVzZXJfaWQiOjIsImlhdCI6IjE1OTA5MTc0OTgiLCJ1c2VyIjoidGlhZ28iLCJkYXRlIjoiMjAyMC0wNS0zMSJ9.XUMvhL13zDZdbjYYPkYnwlZoHN6U7Zc3xUzXsKoVj2I'"
}