簡體   English   中英

DRF中未提供“身份驗證憑據”

[英]“Authentication credentials were not provided.” in DRF

我在DRF后端使用rest_framework_simplejwt身份驗證。 當我使用DRF瀏覽器進行身份驗證並可以訪問預定義的API端點時,一切工作都很好。

但是,當我想以編程方式訪問post / patch方法的端點時,我得不到身份驗證憑據。 錯誤。 這是我的設置:

ALLOWED_HOSTS = ['*']
...
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'propertypost.apps.PropertyConfig',
    'users.apps.UsersConfig',
    'rest_framework',

    # 3rd party
    'django_filters',
    'rest_auth',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'rest_auth.registration',
    'allauth.socialaccount',
    'django.contrib.gis',
]

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 10,
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
        'rest_framework.filters.OrderingFilter',
        'rest_framework.filters.SearchFilter',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',

    ),
    'DEFAULT_PERMISSION_CLASSES': (
        # 'rest_framework.permissions.IsAuthenticated',
    ),
}


...

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=525600),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': True,

    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=120),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}

AUTH_USER_MODEL = 'users.CustomUser'

REST_USE_JWT = True

就像我說的那樣,以上設置在DRF瀏覽器中非常有效,但是當我嘗試請求補丁方法時,它沒有提供身份驗證憑據

AUTH_ENDPOINT = "http://127.0.0.1:8000/rest-auth/login"

data = {
       'username': username,
        'password': password
headers = {
         "Content-Type": "application/json"
 }
 r = requests.post(AUTH_ENDPOINT, data=json.dumps(data), headers=headers)
  token=r.json()['token']
 data = {
        'age': 8,
    }
headers = {
    "Content-Type": "application/json",
    "Authorization": "JWT " + token,
}

r = requests.patch(POST_ENDPOINT, data=json.dumps(data), headers=headers)

請讓我知道我做錯了,謝謝

在“ 用法”部分 ,標題必須采用以下格式

"Authorization: Bearer YourToken"

所以,將標題更改為,

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer " + token,
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM