DRF-未提供身份验证凭据

时间:2018-11-24 07:51:34

标签: django django-rest-framework jwt

我正在使用python请求模块测试django rest框架,但显示错误。我只是rest-api初学者。

DRF设置main.py

import datetime

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        # 'rest_framework.authentication.BasicAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    )
}


JWT_AUTH = {
    'JWT_ENCODE_HANDLER':
    'rest_framework_jwt.utils.jwt_encode_handler',

    'JWT_DECODE_HANDLER':
    'rest_framework_jwt.utils.jwt_decode_handler',

    'JWT_PAYLOAD_HANDLER':
    'rest_framework_jwt.utils.jwt_payload_handler',

    'JWT_PAYLOAD_GET_USER_ID_HANDLER':
    'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',

    'JWT_RESPONSE_PAYLOAD_HANDLER':
    'rest_framework_jwt.utils.jwt_response_payload_handler',

    'JWT_ALLOW_REFRESH': False,
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),

    'JWT_AUTH_HEADER_PREFIX': 'JWT',  # Authorization: JWT <token>
    'JWT_AUTH_COOKIE': None,
}

我的测试代码是

import os
import json
import requests

AUTH_ENDPOINT = 'http://127.0.0.1:8000/api/auth/jwt/'
ENDPOINT = 'http://127.0.0.1:8000/api/status/'

image_path = os.path.join(os.getcwd(), 'drf.png')


headers = {
    "Content-Type": "application/json"
}

data = {
    "username": 'jaki',
    "password": 'SADHIN101119'
}

r = requests.post(AUTH_ENDPOINT, data=json.dumps(data), headers=headers)
token = r.json()['token']

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


post_data = json.dumps({"content": "some random content"})
posted_response = requests.post(ENDPOINT, data=post_data, headers=headers)
print(posted_response.text)

显示错误

  

{“详细信息”:“未提供身份验证凭据。”}

我该如何解决问题。谢谢。

2 个答案:

答案 0 :(得分:1)

Authorization标头中,JWT前缀和令牌必须用空格分隔。将您的Authorization标头更改为:

"Authorization": "JWT " + token

答案 1 :(得分:0)

这是预感...但是请注意

# 'rest_framework.authentication.BasicAuthentication'

当您尝试获取令牌时,您正在使用BasicAuth来发送登录凭据。那可能是失败的。