[英]Djoser simplejwt authentication forbidden(403) while sending JWT <token> to auth/users/me/
我正在使用 djoser 和 simplejwt 進行身份驗證和授權。 當我向端點http://localhost:8000/auth/jwt/create/
發送身份驗證的發布請求時,它會響應訪問和刷新令牌,並且當我再次將Authorization:JWT <access_token>
傳遞給https://localhost:8000/auth/users/me/
它給出了 403 禁止:
"detail": "Authentication credentials were not provided."
有我的設置
DJOSER = { 'LOGIN_FIELD': 'email', 'SEND_CONFIRMATION_EMAIL': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': 'activate/{uid}/{token}', 'PERMISSIONS': { 'activation': ['rest_framework.permissions.AllowAny'], 'password_reset': ['rest_framework.permissions.AllowAny'], 'password_reset_confirm': ['rest_framework.permissions.AllowAny'], 'set_password': ['djoser.permissions.CurrentUserOrAdmin'], 'username_reset': ['rest_framework.permissions.AllowAny'], 'username_reset_confirm': ['rest_framework.permissions.AllowAny'], 'set_username': ['djoser.permissions.CurrentUserOrAdmin'], 'user_create': ['rest_framework.permissions.AllowAny'], 'user_delete': ['djoser.permissions.CurrentUserOrAdmin'], 'user': ['djoser.permissions.CurrentUserOrAdmin'], 'user_list': ['djoser.permissions.CurrentUserOrAdmin'], 'token_create': ['rest_framework.permissions.AllowAny'], 'token_destroy': ['rest_framework.permissions.IsAuthenticated'], }, 'SERIALIZERS': { 'user_create': 'accounts.serializers.UserCreateSerializer', 'user': 'accounts.serializers.UserSerializer' } } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), }
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICAITON_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated' ), }
序列化器
from djoser.serializers import UserCreateSerializer, UserSerializer from django.contrib.auth import get_user_model from rest_framework import serializers User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ('id', 'email', 'first_name', 'last_name', 'password')
用戶 model
from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None, is_staff=False, is_admin=False, is_active=True): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have password") if not first_name: raise ValueError("First Name must be provided") if not last_name: raise ValueError("Last Name must be provided") user = self.model( email=self.normalize_email(email) ) user.set_password(password) # django function change user password user.first_name = first_name, user.last_name = last_name, user.is_staff = is_staff user.is_active = is_active user.is_admin = is_admin user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, password=None): user = self.create_user( email, password=password, first_name=first_name, last_name=last_name, is_staff=True, is_admin=True ) return user def create_staffuser(self, email, first_name, last_name, password=None): user = self.create_user( email, first_name=first_name, last_name=last_name, password=password, is_staff=True ) return user # def get_by_natural_key(self, email_): # return self.get(code_number=email_) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, null=True, blank=True) username = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50) contact_no = models.BigIntegerField(null=True, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email
網址
from django.contrib import admin from django.urls import re_path, path, include from accounts.views import testApi # from sociallogin.views import FacebookLogin, GoogleLogin urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), path('accounts/', testApi), ]
此問題是由於您用於調用端點的 baseUrl ( http://localhost:8000
)。
前端應用程序的 baseUrl 應該與 django 用於啟動開發服務器的那個完全匹配(在我的例子中是http://127.0.0.1:8000/
)。
這是我的設置:
const baseQuery = fetchBaseQuery({
baseUrl: 'http://127.0.0.1:8000/',
prepareHeaders: (headers, {getState}) => {
const access = getState().auth.tokens.access
if (access) {
headers.set('Content-Type', 'application/json')
headers.set('Accept', 'application/json')
headers.set('Authorization', `Bearer ${access}`)
}
return headers
},
})
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"http://127.0.0.1:3000",
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.