我一直在与我附加到OnTokenValidated中的Func做斗争,而不是做它应该做的事情。
在尝试了很多不同的事情之后:
services.Configure<MicrosoftIdentityOptions>(options =>
{
options.Events ??= new OpenIdConnectEvents();
options.Events.OnTokenValidated += context =>
{
context.Principal.AddIdentity(new ClaimsIdentity(new List<Claim> {new Claim("Foo", "Bar")}));
return Task.CompletedTask;
};
}按预期工作,并将值为"Bar“的索赔"Foo”添加到标识中。
但是,只要我在代码中等待一个任务并完成func异步,附加的声明就不会被添加到已签名的标识中:
services.Configure<MicrosoftIdentityOptions>(options =>
{
options.Events ??= new OpenIdConnectEvents();
options.Events.OnTokenValidated += async context =>
{
var someService = context.HttpContext.RequestServices.GetRequiredService<ISomeService>();
var someValue = await someService.SomeMethod();
context.Principal.AddIdentity(new ClaimsIdentity(new List<Claim> {new Claim("Foo", "Bar")}));
};
}不管用。要明确的是,它没有错误,但在方法完成后,附加声明在标识上不存在.
据我所知,通过消除各种因素,使其中断的是等待,然而OnTokenValidated的定义是:
Func<TokenValidatedContext,Task> OnTokenValidated那么它似乎期望处理程序是异步的?
更新: 2022-02-07更进一步:
OnTicketReceived = ctx =>
{
throw new AuthenticationException("Sorry, you cannot log in");
}由于引发异常而导致登录失败,而
OnTicketReceived = async ctx =>
{
throw new AuthenticationException("Sorry, you cannot log in");
}不工作-抛出的异常不影响登录,用户将正确登录,尽管抛出了异常。似乎代码选择已经向前移动,好像堆栈中的某个地方没有等待.然而,看看github上的代码,我在任何地方都找不到堆栈中的异步方法。
更新2022-02-09示例:https://github.com/VaticanUK/msal_so_fail_example
我使用了一个正式的MS示例(可在这里获得:https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2),并使用文档:https://github.com/AzureAD/microsoft-identity-web/wiki/customization#customization-in-the-startupcs中所示的模式在Startup.cs:(https://github.com/VaticanUK/msal_so_fail_example/blob/master/Startup.cs#L40)中添加了MicrosoftIdentityOptions的自定义
要运行这个示例,您需要在Azure中创建一个应用程序,并在appsettings.json中设置您的客户机ID。
如前所述,该示例将工作,我的意思是登录将失败(因为没有异步关键字):

如果添加异步关键字,异常将不会阻止登录:

发布于 2022-02-10 17:41:28
我在MSAL Github帐户上提出了上述问题,在与其中一个贡献者聊天之后,答案是,在包含事件处理程序的选项的注册过程中,它需要注册为:
services.Configure<MicrosoftIdentityOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>而不是:
services.Configure<MicrosoftIdentityOptions>(options =>因此,有效的正式登记是:
services.Configure<MicrosoftIdentityOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Events ??= new OpenIdConnectEvents();
options.Events.OnTokenValidated += async context =>
{
var someService = context.HttpContext.RequestServices.GetRequiredService<ISomeService>();
var someValue = await someService.SomeMethod();
context.Principal.AddIdentity(new ClaimsIdentity(new List<Claim> {new Claim("Foo", "Bar")}));
};
}目前,我不明白这是如何解决这个问题的,或者为什么不让身份验证方案作为注册的名称,只会使它同步工作,但它解决了我的问题,所以出于知识的好奇心,我很可能会尝试找出问题的根源,但是上面的这些都解决了眼前的问题!
https://stackoverflow.com/questions/71012036
复制相似问题