简体   繁体   English

DRF-未提供身份验证凭据

[英]DRF - Authentication credentials were not provided

I am testing django rest framework using python requests module but its says an error. 我正在使用python请求模块测试django rest框架,但提示错误。 I am just beginner rest-api developer. 我只是rest-api新手开发人员。

DRF setting main.py 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,
}

and my testing code is 我的测试代码是

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)

Error showing 显示错误

{"detail":"Authentication credentials were not provided."} {“详细信息”:“未提供身份验证凭据。”}

How can i solve the problem. 我该如何解决这个问题。 Thanks. 谢谢。

In the Authorization header, the JWT prefix and token must be separated with a space. Authorization标头中, JWT前缀和令牌必须用空格分隔。 Change your Authorization header to: 将您的Authorization标头更改为:

"Authorization": "JWT " + token

This aa hunch ... but uncomment out 这是一个预感...但没有评论

# 'rest_framework.authentication.BasicAuthentication'

When you're trying to get your Token, you're using BasicAuth to send over your login creds. 当您尝试获取令牌时,您正在使用BasicAuth来发送登录凭据。 That's probably failing. 那可能是失败的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM