繁体   English   中英

Django Rest 框架 + React JWT 身份验证,403 禁止在受保护的视图上

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM