【问题标题】:Execute code after Azure AD AuthenticationAzure AD 身份验证后执行代码
【发布时间】:2019-09-02 16:54:24
【问题描述】:

我能够让这个例子工作https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-openidconnect-aspnetcore/

我的问题是如何在身份验证后做一些额外的事情。例如,在一个典型的登录页面上,在验证后的 POST 中,我可以为用户设置日志记录或设置额外的 cookie。

通过 Azure AD 集成,我不确定将这些代码放在哪里,这些代码只有在用户通过身份验证后才应该执行。回复 URL(回调路径)不适用于此目的(我尝试将自定义页面放在这里,但它确实没有被执行。显然,中间件为该端点创建了一个特殊的路由,以便它可以处理登录令牌数据)

感谢任何帮助!

【问题讨论】:

    标签: asp.net-core azure-active-directory openid-connect


    【解决方案1】:

    有一些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 可用于在身份验证期间向用户添加自定义声明。请查看以上文档以获取更多活动。

    【讨论】:

    猜你喜欢
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 2020-12-27
    • 2021-11-26
    • 2019-10-15
    • 1970-01-01
    相关资源
    最近更新 更多