簡體   English   中英

DRF-未提供身份驗證憑據

[英]DRF - Authentication credentials were not provided

我正在使用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)

顯示錯誤

{“詳細信息”:“未提供身份驗證憑據。”}

我該如何解決這個問題。 謝謝。

Authorization標頭中, JWT前綴和令牌必須用空格分隔。 將您的Authorization標頭更改為:

"Authorization": "JWT " + token

這是一個預感...但沒有評論

# 'rest_framework.authentication.BasicAuthentication'

當您嘗試獲取令牌時,您正在使用BasicAuth來發送登錄憑據。 那可能是失敗的。

暫無
暫無

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

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