401 错误访问受保护的 Azure AD API react-adal

401 Error accessing Azure AD protected API with react-adal

我正在尝试使用 Azure AD Auth 在 Azure 中设置一个带有 React 前端 + .NET Core 后端的应用程序。后端将调用其他 API 并持有一些逻辑。我设置了 .NET Core 应用程序并将其托管在 Azure 应用程序服务中,然后使用 the connected services wizard in visual studio, which generated code similar to what is on this tutorial(后端部分)添加身份验证:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(sharedOptions =>
    {
        sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddAzureAdBearer(options => Configuration.Bind("AzureAd", options));
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication();
...
}

appsettings.json(假身份证):

"AzureAd": {
    "ClientId": "1fff1098-3bc0-40d9-8cd0-e47b065085b6",
    "Domain": "mytenant.onmicrosoft.com",
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "mytenantid",
    "AppIDURL": "https://my-api.azurewebsites.net/",
    "ConfigView": "API"
}

然后我在前端设置 react-adal:

{
  tenant: "mytenant.onmicrosoft.com",
  clientId: "1fff1098-3bc0-40d9-8cd0-e47b065085b6",
  endpoints: {
    api: "1fff1098-3bc0-40d9-8cd0-e47b065085b6"
  },
  cacheLocation: "localStorage"
};

里面我是按照github instructions的设置来设置react-adal的。登录按预期工作,但是当我 运行 adalApiFetch 针对我的后端时,我收到 401 错误,说明 = 签名无效。我可以在调试器上看到发送了授权 header(Bearer + token)。关于我在这里可能做错了什么的任何想法?提前致谢!

我正在测试的端点是一个简单的测试控制器(带有 [Authorize]),它只是 returns "Authentication Tested".

一段时间后我找到了我的错误并返回 post 解决方案。问题是我使用了不正确的 method/settings(不匹配)。从问题的代码:如果使用 sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;,那么您还应该使用具有适当配置选项的 AddJwtBearer(在此处找到:JwtBearerOptions),而不是 AddAzureAdBearer。就我而言,最终更正的启动代码是

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
        .AddAzureADBearer(options => Configuration.Bind("AzureAd",options));
....

具有相应的设置(在此处找到:AzureADOptions