令牌认证返回 403(Axios + Django Rest Framework) [英] Token Authentication returning 403 (Axios + Django Rest Framework)

查看:95
本文介绍了令牌认证返回 403(Axios + Django Rest Framework)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been trying to fix this for a few hours now, please help me if you can.

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

When I try to make get requests w/ axios in my React app to my DRF Rest API it returns 403.

App.js:

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

settings.py:

settings.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 端点.

I have a posts endpoint that only authenticated users can see.

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

After logging in from within my React APP this token was generated. (using plain text for now because I'm testing)

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

So, when I try to make a get request with it, it returns the following error:

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

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

Why is this happening? Do I need to send any more information via the Header? I have read other questions and the documentation but can't find an answer.

谢谢.

推荐答案

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

Ok, I managed to find out what was wrong. I had to allow TokenAuthentication in my app.

所以我所做的是:

settings.py

settings.py

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

views.py

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

在那之后它工作得很好.

After that it worked just fine.

希望对大家有所帮助.

这篇关于令牌认证返回 403(Axios + Django Rest Framework)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆