有一些OpenIdConnectEvents 可用于使开发人员能够控制身份验证过程。
例如,如果协议消息中存在授权代码,则在安全令牌验证后调用OnAuthorizationCodeReceived。该事件可用于获取访问令牌,以便在代码/混合流中使用 ADAL/MSAL 的授权代码访问 API:
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
{
// Acquire a Token for the Graph API and cache it using ADAL. In the TodoListController, we'll use the cache to acquire a token for the Todo List API
string userObjectId = (context.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
var authContext = new AuthenticationContext(context.Options.Authority, new NaiveSessionCache(userObjectId, context.HttpContext.Session));
var credential = new ClientCredential(context.Options.ClientId, context.Options.ClientSecret);
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(context.TokenEndpointRequest.Code,
new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, context.Options.Resource);
// Notify the OIDC middleware that we already took care of code redemption.
context.HandleCodeRedemption(authResult.AccessToken, context.ProtocolMessage.IdToken);
}
代码示例链接:Calling a web API in an ASP.NET Core web application using Azure AD.
OnTokenValidated 可用于在身份验证期间向用户添加自定义声明。请查看以上文档以获取更多活动。