【问题标题】:Azure SSO OnTokenValidated is not workingAzure SSO OnTokenValidated 不起作用
【发布时间】:2020-09-21 11:51:33
【问题描述】:
我在 .net core 3.1 startups.cs 类上使用以下代码。它没有达到下面的线。就我而言,我从 Azure AD 获取令牌并想检查用户是否存在于我们的应用程序数据库(外部数据库)中。下面是我正在使用的示例代码
services.AddProtectedWebApi(Configuration);
services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
{
var existingOnTokenValidatedHandler = options.Events.OnTokenValidated;
options.Events.OnTokenValidated = async context =>
{
await existingOnTokenValidatedHandler(context);
context.Fail("user not avilable in database");
// your code to add extra claims that will be executed after the current event implementation.
};
});
【问题讨论】:
标签:
c#
azure
single-sign-on
asp.net-core-webapi
【解决方案1】:
Microsoft.Identity.Web 中 JwtBearerOptions 的默认身份验证方案是 JwtBearerDefaults.AuthenticationScheme(“Bearer”),如 documet for AddProtectedWebApi method 中所述。身份验证方案 AzureADDefaults.JwtBearerAuthenticationScheme(“AzureADJwtBearer”)未注册,因此被忽略。
通过将 AzureADDefaults.JwtBearerAuthenticationScheme 替换为 JwtBearerDefaults.AuthenticationScheme 来更新代码,如下所示:
services.AddProtectedWebApi(Configuration);
services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
var existingOnTokenValidatedHandler = options.Events.OnTokenValidated;
options.Events.OnTokenValidated = async context =>
{
await existingOnTokenValidatedHandler(context);
context.Fail("user not avilable in database");
// your code to add extra claims that will be executed after the current event implementation.
};
});
另一种扩展自定义令牌验证的方法可以在下面的代码中找到:
services.AddProtectedWebApi(options =>
{
Configuration.Bind("AzureAd", options);
options.Events = new JwtBearerEvents();
options.Events.OnTokenValidated = async context =>
{
//your code for additional validation.
};
},
options =>
{
Configuration.Bind("AzureAd", options);
});