【问题标题】:Test with postman get error 401 Unauthorized even if Azure AD Authentication is OK即使 Azure AD 身份验证正常,使用邮递员进行测试也会得到错误 401 Unauthorized
【发布时间】:2021-10-04 00:32:51
【问题描述】:

我在 .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 并注册了一个新应用:

  2. 我配置了平台

  3. 我添加了邮递员的秘密

现在,我打开邮递员并为我的测试配置身份验证:

当我点击 Get New Access Token 时,我得到了正确的结果:

但是现在,如果我调用我的 API,我会收到 401 Unauthorized 错误:

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

谢谢

【问题讨论】:

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


    【解决方案1】:

    解决方案 1:确保在请求身份验证令牌时指定资源参数。没有参数你仍然会得到令牌,但是会出现 401 错误,因为没有有效的资源。

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

    解决方案 3:还要确保服务中提到的 App ID URI。

    转到应用服务 > 身份验证刀片 > 高级设置

    更多详情请参考link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-24
      • 1970-01-01
      • 2022-12-03
      • 2018-05-07
      相关资源
      最近更新 更多