作者:-断桥再见-_974_328 | 来源:互联网 | 2022-12-10 11:50
1> mthierba..:
我可能在这里参加聚会有点晚,但是我遇到了同样的问题,发现AzureAD身份验证中间件的文档非常稀疏。在这里为其他遇到相同问题的人添加解决方案。
正如你可以在这个问题的代码片段的底部看到,AzureAD提供商实际上依赖于OpenIdConnect
与COOKIE
头套下AUTH提供商,并没有实现任何验证逻辑本身。
为此,添加了两个附加的身份验证方案,分别使用定义为AzureADDefaults.OpenIdScheme
和的名称AzureADDefaults.COOKIEScheme
。
(尽管使用AddAzureAD(this Microsoft.AspNetCore.Authentication.AuthenticationBuilder builder, string scheme, string openIdConnectScheme, string COOKIEScheme, string displayName, Action configureOptions)
重载时也可以自定义名称)。
进而允许配置有效的名称,OpenIdConnectOptions
并COOKIEAuthenticationOptions
使用上方的方案名称,包括访问OpenIdConnectEvents
。
请参阅以下完整示例:
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(optiOns=> Configuration.Bind("AzureAd", options));
services.Configure(AzureADDefaults.OpenIdScheme, optiOns=>
{
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider= async ctxt =>
{
// Invoked before redirecting to the identity provider to authenticate. This can be used to set ProtocolMessage.State
// that will be persisted through the authentication process. The ProtocolMessage can also be used to add or customize
// parameters sent to the identity provider.
await Task.Yield();
},
OnMessageReceived= async ctxt =>
{
// Invoked when a protocol message is first received.
await Task.Yield();
},
OnTicketReceived= async ctxt =>
{
// Invoked after the remote ticket has been received.
// Can be used to modify the Principal before it is passed to the COOKIE scheme for sign-in.
// This example removes all 'groups' claims from the Principal (assuming the AAD app has been configured
// with "groupMembershipClaims": "SecurityGroup"). Group memberships can be checked here and turned into
// roles, to be persisted in the COOKIE.
if (ctxt.Principal.Identity is ClaimsIdentity identity)
{
ctxt.Principal.FindAll(x => x.Type == "groups")
.ToList()
.ForEach(identity.RemoveClaim);
}
await Task.Yield();
},
};
});
services.Configure(AzureADDefaults.COOKIEScheme, optiOns=>
{
options.Events = new COOKIEAuthenticationEvents
{
// ...
};
});