【问题标题】:Capture event after initial ASPNET MVC Client authentication to IdentityServer4?在对 IdentityServer4 进行初始 ASPNET MVC 客户端身份验证后捕获事件?
【发布时间】:2017-10-03 22:08:30
【问题描述】:

我有一个 ASP.NET MVC 客户端连接到 IdentityServer4。

我使用 [Authorize] 装饰来启动对 IdentityServer 登录的调用,然后在成功登录后正确重定向回我的客户端应用程序。

但是在这次成功登录之后,我想执行一些额外的操作(例如在客户端数据库中记录 LastLoginDateTime,在客户端数据库中更新一些角色信息,等等...)。

应该使用什么事件,只有在 IdentityServer 正确验证并传回客户端应用程序时才会触发?

我一直在尝试自定义 AuthorizeAttribute,但这会在每个控制器操作上触发(并且在后续触发时似乎也会丢失声明):

public class CustAuthorize : AuthorizeAttribute
{
    public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            //grab information about User
            var user = filterContext.HttpContext.User as ClaimsPrincipal;
            var UserID_portal = (from p in user.Claims where p.Type == "sub" select p.Value).FirstOrDefault();

            //perform additional database stuff here...
        }
    }
}

*********编辑 - 已更新答案 ***********

根据下面提供的公认答案,如果您使用的是 Microsoft.Owin.Security.OpenIdConnect,Version=3.0.1.0,您的事件处理程序将如下所示:

 Notifications = new OpenIdConnectAuthenticationNotifications()
 {
      SecurityTokenValidated = (context) =>
      {
           System.Security.Claims.ClaimsIdentity identity = context.AuthenticationTicket.Identity;
      }
 }

【问题讨论】:

    标签: c# asp.net-mvc identityserver4


    【解决方案1】:

    假设您使用的是 Microsoft OpenID Connect 中间件:

    您可以在OpenIdConnectOptions 上使用Events 属性。这允许您在身份验证 OpenID Connect 过程中挂钩特定事件并执行自定义逻辑。所以你会做这样的事情:

    Events = new OpenIdConnectEvents {
      OnTokenValidated = async x => {
        /* update records */
      }
    }
    

    【讨论】:

    • 谢谢 - 这正是我所需要的。我想我使用的是旧版本的 Microsoft.Owin.Security.OpenIdConnect (3.0.1),所以我不得不使用 OpenIdConnectAuthenticationOptions 而不是 OpenIdConnectOptions。 (顺便说一句,你的教程scottbrady91.com/Identity-Server/… 是任何开始使用 IdentityServer4 的人的必读之物。)
    猜你喜欢
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 2012-01-10
    相关资源
    最近更新 更多