首页 文章

使用Azure B2C进行.NET核心JWT验证

提问于
浏览
1

我对 Azure B2C 的令牌验证有问题 . 错误是:

AuthenticationFailed:IDX10205:颁发者验证失败 . 发行人:'[PII默认隐藏 . 将IdentityModelEventSource.cs中的'ShowPII'标志设置为true以显示它 . ]' . 不匹配:validationParameters.ValidIssuer:'[PII默认隐藏 . 将IdentityModelEventSource.cs中的'ShowPII'标志设置为true以显示它 . ]'或validationParameters.ValidIssuers:'[PII默认隐藏 . 将IdentityModelEventSource.cs中的'ShowPII'标志设置为true以显示它 . ]' .

在我的 .net core webapi 项目中,我从Nuget添加了 System.IdentityModel.Tokens.Jwt . 然后在 ConfigureServices 下的Startup.cs中我添加了:

services.AddAuthentication(options =>
  { 
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; 
  })
  .AddJwtBearer(jwtOptions =>
  {
    jwtOptions.Authority = 
         $"https://login.microsoftonline.com/tfp/{Configuration["B2CTenantId"]}/" + 
         "{Configuration["B2CPolicy"]}/v2.0/";
    jwtOptions.Audience = Configuration["B2CClientId"];
    jwtOptions.Events = new JwtBearerEvents
    {
      OnAuthenticationFailed = AuthenticationFailed
    };
  });

  private Task AuthenticationFailed(AuthenticationFailedContext arg)
  {
        // For debugging purposes only!
        var s = $"AuthenticationFailed: {arg.Exception.Message}";
        arg.Response.ContentLength = s.Length;
        arg.Response.Body.Write(Encoding.UTF8.GetBytes(s), 0, s.Length);

        return Task.FromResult(0);
  }

其中 B2CTenandId 类似于 mytenant.onmicrosoft.comB2CClientId 是来自Azure门户的if和 B2CPolicyb2c_1_susi (为登录创建) .

Azure B2C configuration

1 回答

  • 2

    正确的配置是

    var cnn = $"https://login.microsoftonline.com/tfp/{Configuration["B2CTenantId"]}/" +
              $"{Configuration["B2CPolicy"]}/v2.0/";
    

    B2CTenant 是您的域名 mydomain.onmicrosoft.com . B2CPolicy 是您在 Azure Portal 中创建的策略(请参阅问题中的我的图像) .

相关问题