【问题标题】:Sending Azure token to API back-end keeps returning 401 Unauthorzied error when OnTokenValidated is added to the API将 OnTokenValidated 添加到 API 时,向 API 后端发送 Azure 令牌不断返回 401 Unauthorzied 错误
【发布时间】:2018-04-18 15:17:19
【问题描述】:

最近我们创建了一个 React 前端,它按照本教程与我们的 API 后端进行通信:https://itnext.io/a-memo-on-how-to-implement-azure-ad-authentication-using-react-and-net-core-2-0-3fe9bfdf9f36

就像在教程中一样,我们在前端使用 adal-react 库设置了身份验证。我们在 azure 中添加/注册了前端。

接下来我们创建了我们的 API (.Net Core 2) 并在 azure 环境中注册了它,配置在 appsettings 中设置:

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantDomain": "our_azure_environment.onmicrosoft.com",
    "TenantId": "our_azure_environment.onmicrosoft.com",
    "ClientId": "our_front-end_azure_id_1234"
  }

在 API 中,我们还在 ConfigureServices 中添加了 JWT 中间件,如下所示:

 services.AddAuthentication(sharedOptions =>
             {
                 sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;

             })
             .AddJwtBearer(options =>
             {
                 options.Audience = Configuration["AzureAd:ClientId"];
                 options.Authority = $"{Configuration["AzureAd:Instance"]}{Configuration["AzureAd:TenantId"]}";

             });

在登录前端工作后进行测试(从前端调用端点)时,正在返回数据并验证用户(api端点具有Authorize属性),当未登录时api 端点返回 401(应该如此)。

问题如下: 当我将以下代码添加到 API ConfigureServices 时(我想在身份验证后使用它来做一些额外的事情):

options.Events = new JwtBearerEvents()
                 {
                     OnTokenValidated = context =>
                     {

                         //Check if user has a oid claim
                         if (!context.Principal.HasClaim(c => c.Type == "oid"))
                         {
                             context.Fail($"The claim 'oid' is not present in the token.");
                         }
                         return Task.CompletedTask;
                     }
                 };

突然,对 API 端点的调用在登录时返回 401 (Unauthorized) 错误。不过,如果我删除 OnTokenValidated 部分,它可以正常工作。

到达OnTokenValidated 时,令牌应该已经过验证/认证,还是我错了? IntelliSense 还说; Invoked after the security token has passed validation and a ClaimsIdentity has been generated.

我忘了添加一些设置吗?我的感觉告诉我,这可能是天蓝色本身的错误设置,但我实际上不知道。

从前端发送到 API 的同一个令牌也被发送到图 API,当这样做时,图要求给予同意,同意后它可以工作。考虑到这一点,我相信我应该为 API 或其他东西添加一些权限,但我不确定。

更新

juunas 在下面的评论中指出我使用了错误的ClaimsPrincipal value 这解决了最初的问题,但现在下面给了我 401 错误:

在我的 ConfigureServicesAddAuthentication 部分之前)中,我添加了以下内容来管理/添加用户到我的 AspNetUsers 表(在我的 azure 数据库中):

 services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<TRSContext>()
                .AddDefaultTokenProviders();

将此代码添加到管道时,我再次在前端收到 401 错误。任何线索这是为什么?

更新2

我找到了上述解决方案(更新)。这是由于AddIdentity 接管了来自 JWT 的身份验证引起的。这可以通过添加来避免:

  • Options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  • Options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

.AddAuthentication 选项:

services.AddAuthentication(Options =>
             {
                 Options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                 Options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 
                 Options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 
             })

有关上述内容的更多信息可在此处找到: https://github.com/aspnet/Identity/issues/1376

【问题讨论】:

  • 嗯,一个问题可能是您正在寻找类型为"oid" 的声明,但.NET ClaimsPrincipal 会将其转换为"http://schemas.microsoft.com/identity/claims/objectidentifier"。试试吧:)
  • @juunas 非常感谢,这修复了错误。但是,现在我在后续代码中遇到错误。也许您对此也有一些有用的意见(在主帖中作为更新发布)。
  • 那个我不知道为什么会这样:/

标签: reactjs azure asp.net-core


【解决方案1】:

第一种情况出现错误是因为 .NET ClaimsPrincipal 对象将 oid 声明类型转换为:http://schemas.microsoft.com/identity/claims/objectidentifier

所以它需要是这样的:

options.Events = new JwtBearerEvents()
{
    OnTokenValidated = context =>
    {
        //Check if user has a oid claim
        if (!context.Principal.HasClaim(c => c.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier"))
        {
            context.Fail($"The claim 'oid' is not present in the token.");
        }
        return Task.CompletedTask;
    }
};

【讨论】:

    猜你喜欢
    • 2021-01-31
    • 2014-02-08
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    相关资源
    最近更新 更多