繁体   English   中英

令牌认证返回 403(Axios + Django Rest 框架)

[英]Token Authentication returning 403 (Axios + Django Rest Framework)

我已经尝试解决这个问题几个小时了,如果可以的话,请帮助我。

当我尝试在我的 React 应用程序中使用 axios 向我的 DRF Rest API 发出get请求时,它返回 403。

应用程序.js:

      axios
        .get(API_POSTS, {
          headers: {
            Authorization: `Token 27dbb4dd8299792c8c52022f829da4ecec22f437`
          }
        })
        .then(res => {
          console.log("Success");
        })
        .catch(error => {
          console.log(error);
        });

设置.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    # 3rd-party apps
    'rest_framework',
    'rest_framework.authtoken',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'rest_auth',
    'rest_auth.registration',
    'corsheaders',
    # Local
    'posts.apps.PostsConfig',
    'users.apps.UsersConfig',
]

CORS_ORIGIN_WHITELIST = [
    'http://localhost:3000',
]

# Rest Framework


REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication'
    ],
}

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
)

SITE_ID = 1

REST_AUTH_REGISTER_SERIALIZERS = {
    'REGISTER_SERIALIZER': 'users.serializers.CustomRegisterSerializer',
}

我有一个posts端点,只有经过身份验证的用户才能看到。

从我的 React APP 中登录后,生成了这个令牌。 (现在使用纯文本,因为我正在测试)

因此,当我尝试使用它发出 get 请求时,它会返回以下错误:

Error: Request failed with status code 403
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:60)

为什么会这样? 我是否需要通过 Header 发送更多信息? 我已阅读其他问题和文档,但找不到答案。

谢谢你。

好的,我设法找出问题所在。 我必须在我的应用程序中允许TokenAuthentication

所以我所做的是:

设置.py

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': (
   'rest_framework.authentication.TokenAuthentication',
   )
}

视图.py

class PostList(generics.ListCreateAPIView):
    authentication_classes = (TokenAuthentication, )
    queryset = Post.objects.all()
    serializer_class = PostSerializer

之后它工作得很好。

希望对大家有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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