[英]Django Rest Framework + React JWT authentication, 403 Forbidden on protected views
我正在嘗試使用 DRF + react 制作一個 CRUD 網站,我在某種程度上遵循了本教程進行身份驗證
https://hackernoon.com/110percent-complete-jwt-authentication-with-django-and-react-2020-iejq34ta (有一些差異,因為我完全分開使用 DRF 和 React)
身份驗證很好,我已經可以登錄、注銷和注冊,但是任何需要“IsAuthenticated”權限的視圖都會給我一個 403 Forbidden,我也嘗試使用標題通過 postman 獲取數據:Accept: application/json Authorization :JWT“myaccesstoken”,但我也收到帶有“詳細信息”的 403:“您無權執行此操作。”
這是一些代碼
Settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication', (#I've already tried commenting out basic and session auth)
)
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=14),
'ROTATE_REFRESH_TOKENS': True,
'BLACKLIST_AFTER_ROTATION': True,
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'VERIFYING_KEY': None,
'AUTH_HEADER_TYPES': ('JWT ',),
'USER_ID_FIELD': 'username',
'USER_ID_CLAIM': 'user_id',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
}
CORS_ORIGIN_ALLOW_ALL = True
和受保護的視圖
views.py
class PostList(generics.ListCreateAPIView):
permission_classes = (IsAuthenticated,) (#I've tried with or without this)
authentication_classes = () (# if i take this out i get a 401 insteand of a 403)
queryset = Post.objects.all()
serializer_class = PostSerializer
我沒有顯示任何反應代碼,因為我認為問題出在 DRF 部分,因為我也無法在 PostMan 上成功發出 GET 請求,如果我將設置更改為 AllowAny,我可以在這兩個地方發出 GET 請求正好
我也有同樣的問題。 似乎用於默認身份驗證的 REST_FRAMEWORK 設置(特別是 rest_framework_simplejwt)不起作用。 我不知道為什么...
嘗試在您的 authentication_classes 元組中直接導入 JWTAuthentication class ,例如:
from rest_framework_simplejwt.authentication import JWTAuthentication
class PostList(generics.ListCreateAPIView):
permission_classes = (IsAuthenticated,)
authentication_classes = (JWTAuthentication)
queryset = Post.objects.all()
serializer_class = PostSerializer
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.