簡體   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