azure - 使用 postman 进行测试,即使 Azure AD 身份验证正常,也会出现错误 401 未经授权

标签 azure asp.net-web-api azure-active-directory .net-5

我在 .NET 5 中创建了一个 Web API,然后将其发布到 Azure 上。

以下是我在启动时配置 Web API 的方法:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMicrosoftIdentityWebApiAuthentication(Configuration, "AzureAd");
    ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints
            .MapControllers()
            .RequireAuthorization();
    });
}

这就是 appsettings.json:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "***.com", //Domain name configured in Azure  
  "TenantId": "***", // Tenant Id configured in Azure  
  "ClientId": "***", //  Client Id configured in Azure  
  "CallbackPath": "/signin-oidc"
}

现在我启用了 Azure AD 身份验证。步骤如下:

  1. 我在 Azure AD 上注册了一个新应用程序: enter image description here

  2. 我配置了平台

  3. 我添加了 postman 的 secret enter image description here

现在,我打开 postman 并为我的测试配置身份验证: enter image description here

当我单击“获取新访问 token ”时,我得到了正确的结果: enter image description here

但是现在,如果我调用 API,我会收到 401 未经授权的错误: enter image description here

我的配置还有什么问题吗?请问有什么帮助吗?

谢谢

最佳答案

解决方案 1:确保在请求身份验证 token 时指定资源参数。如果没有参数,您仍然可以获得 token ,但会出现 401 错误,因为没有有效的资源。

enter image description here

解决方案 2:将授权数据添加到请求 header 。

enter image description here

解决方案 3:同时确保服务中提到的应用 ID URI。

转至应用服务 > 身份验证边栏选项卡 > 高级设置

enter image description here

有关更多详细信息,请参阅此 link

关于azure - 使用 postman 进行测试,即使 Azure AD 身份验证正常,也会出现错误 401 未经授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68557483/

相关文章:

azure - 如何在存储资源管理器中使用 SAS URI 将文件夹上传到 Blob 存储

c# - Azure函数 "Unable to find assembly"

c# - WebAPI 异步方法错误

angular - Azure AD 2.0 应用程序 - 无法从 Angular 客户端访问范围

azure - 无需凭据即可向 Azure AD 进行身份验证

azure - 从 Azure Active Directory 获取员工 ID

C++ - 使用在 azure 中托管的 C# REST-full WCF 服务

Azure网络应用程序: The `Https` version of URL throws `ERR_CONNECTION_RESET`

.net - Web API Swagger 文档导出为 PDF

c# - 发布到 Web API 时出现不支持的媒体类型错误