“未提供身份验证凭据。”在DRF中

时间:2019-03-19 04:09:27

标签: django django-rest-framework jwt

我在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)

请让我知道我在做什么错 谢谢,

1 个答案:

答案 0 :(得分:0)

Usage section中,标头必须采用以下格式

"Authorization: Bearer YourToken"

因此,将标题更改为

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