.net核心B2C /第三方JWT验证和授权

时间:2020-07-08 16:03:56

标签: asp.net .net-core jwt-auth

.net核心Web API v3.1

使用Azure B2C对用户进行身份验证,并拥有一些直接工作流之外的.net core 3.1 API。经过身份验证的服务将呼叫我的端点。几乎所有这些都是服务器到服务器的。

我需要验证令牌,声明,到期时间等。如何最好地做到这一点?我可以单独使用令牌在.net核心API中“认证”用户/调用者吗?我可以使用[Authorize]属性保护端点吗?我希望避免需要直接与Azure B2C连接,而只是依赖令牌。

我发现所有JWT / .net核心API示例都包括直接通过B2C进行身份验证的客户端。有关如何实现此目标的任何建议?

1 个答案:

答案 0 :(得分:0)

在我的情况下,用户使用OAuth2针对第三方在应用中对应用进行交互身份验证,并检索JWT。

然后,应用程序使用此令牌请求ASP.NET Core Web API(.net Core 3.1)。 API控制器具有[Authorize]属性,并且使用Azure B2C身份验证检查令牌。

我不知道这是否完全符合您的情况。但是由于花了我很多时间才能开始运行,所以我认为这可能会给您提示。

这就是我设置JWT身份验证的方式。

// In the startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    string clientId = "<guid-identifying-the-client>"
    string policy = "B2C_1A_Sample_Policy"
    string tenant = "sampletenant.onmicrosoft.com"
    string aadInstance = $"https://login.microsoftonline.com/{tenant}/v2.0/.well-known/openid-configuration?p={policy}"

    services.AddAuthentication(opt =>
        {
            opt.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(jwtOpt =>
        {
            jwtOpt.TokenValidationParameters = new TokenValidationParameters
            {
                ValidAudience = clientId,
                AuthenticationType = policy
            };
            jwtOpt.ConfigurationManager =
                new ConfigurationManager<OpenIdConnectConfiguration>(
                    aadInstance, 
                    new OpenIdConnectConfigurationRetriever())
                    {
                        RefreshInterval = new TimeSpan(0, 5, 0)
                    };
            });
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //...
    app.UseAuthentication();
    app.UseAuthorization();
    //...
}

注意:上面的示例中使用的aad实例为deprecated,需要迁移到b2clogin.com,直到2020年12月4日。