首页 > 解决方案 > 为什么我总是得到“服务器已拒绝客户端凭据。” 当我调用业务中心 api 时?

问题描述

这是我的 MSAL 身份验证:

@app.route('/get-microsoft-data', methods=('GET', 'POST'))
def get_microsoft_token():
    public_app = ConfidentialClientApplication(
        client_id="<client_id>", authority="https://login.microsoftonline.com/<tenant_id>",
        client_credential="<client_secret>"
    )
    
    result = None
    result = public_app.acquire_token_silent(["https://api.businesscentral.dynamics.com/.default"], account=None)

    if not result:
        print("No suitable token exists in cache. Let's get a new one from AAD.")
        result = public_app.acquire_token_for_client(scopes=["https://api.businesscentral.dynamics.com/.default"])
        
    if "access_token" in result:
        global microsoft_token
        microsoft_token = result["access_token"]

    return redirect('/') 

这是我对业务中心 API 的调用:

@app.route('/send-data-to-microsoft', methods=('GET', 'POST'))
def send_data_to_microsoft():
    print(microsoft_token)
    
    headers = {
        "Authorization": "Bearer " + microsoft_token
    }
    
    r = requests.get("https://api.businesscentral.dynamics.com/v1.0/<tenant_domain>/sandbox/api/v1.0/companies", headers=headers)
    print(r.json())
    return redirect('/')

这是我在调用 /send-data-to-microsoft 时遇到的错误:

{'error': {'code': 'Authentication_InvalidCredentials', 'message': 'The server has rejected the client credentials.  CorrelationId:  ff4d9d32-db03-4c2a-bf77-2e6186d4988c.'}}

这是我想要的文档:https ://docs.microsoft.com/en-us/dynamics-nav/api-reference/v1.0/api/dynamics_companies_get

这是业务中心的有效端点列表:https ://docs.microsoft.com/en-us/dynamics-nav/api-reference/v1.0/endpoints-apis-for-dynamics

标签: pythonazuremsaldynamics-business-central

解决方案


此处不支持客户端凭据流。根据官方文档,Dynamics 365 BC 支持的身份验证方法只有这 2 个选项:

  • 基础认证
  • AAD 身份验证

如果您想使用不需要用户交互的方法调用 D365 BC API,您应该选择Basis Authentication

这样做的步骤是:

  1. 要设置基本身份验证,请登录您的租户,并在搜索字段中输入用户,然后选择相关链接。
  2. 选择要为其添加访问权限的用户,然后在 User Card 页面上的 Web Service Access Key 字段中生成一个密钥。
  3. 复制生成的密钥并将其用作用户名的密码。

然后你可以参考Exploring the APIs with Postman and basic authentication


推荐阅读