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

问题描述 投票:2回答: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

c# azure azure-ad-b2c
1个回答
2
投票

正确的配置是

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

B2CTenant是你的域名mydomain.onmicrosoft.comB2CPolicy是您在Azure Portal创建的政策(请参阅我在问题中的图片)。

© www.soinside.com 2019 - 2024. All rights reserved.