【问题标题】:.net core B2C / 3rd party JWT validation and authorization.net core B2C / 3rd 方 JWT 验证和授权
【发布时间】:2020-10-29 02:30:04
【问题描述】:
.net core web api v3.1
使用 Azure B2C 对用户进行身份验证,并拥有一些在该直接工作流之外的 .net core 3.1 API。经过身份验证的服务将调用我的端点。几乎所有这些都是服务器到服务器。
我需要验证令牌、声明、过期等。我怎样才能最好地做到这一点?我可以单独使用令牌在我的 .net 核心 API 中“验证”用户/调用者吗?我可以使用 [Authorize] 属性保护我的端点吗?我希望避免直接与 Azure B2C 连接的需要,而只是依赖令牌。
我发现的所有 JWT / .net 核心 API 示例都包括直接使用 B2C 进行身份验证的客户端。关于如何完成此任务的任何建议?
【问题讨论】:
标签:
asp.net
.net-core
jwt-auth
【解决方案1】:
在我的场景中,用户使用 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,需要在 2020 年 12 月 4 日之前迁移到 b2clogin.com