Search code examples
c#asp.net-mvcidentityserver4

Capture event after initial ASPNET MVC Client authentication to IdentityServer4?


I have an ASP.NET MVC client connecting to IdentityServer4.

I use the [Authorize] decoration to initiate the call to IdentityServer login, which then properly redirects back to my client application after successful login.

But after this successful login, I would like to perform some additional actions (such as log the LastLoginDateTime in the client database, update some role information in the client database, etc...).

What event should be used that will only fire when the IdentityServer correctly authenticates and passes back to the client application?

I have been trying a custom AuthorizeAttribute, but this fires on every controller action (and also seems to lose the Claims on subsequent firing):

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...
        }
    }
}

*********EDIT - UPDATED WITH ANSWER ***********

Based off of the accepted answer provided below, if you are using Microsoft.Owin.Security.OpenIdConnect, Version=3.0.1.0, your event handler would look like this:

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

Solution

  • Assuming you are using the Microsoft OpenID Connect middleware:

    You can use the Events property on the OpenIdConnectOptions. This allows you to hook into specific events in the authentication OpenID Connect process and perform custom logic. So you'll be doing something like:

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