Search code examples
c#authenticationasp.net-coreidentityserver4

ASP Core Intercept All Authentication Requests


EDIT I'm looking for a generic way to intercept authentication requests, there should be a way to globally configure this, using middle-ware or events etc, unrelated to the framework that I am using(IdentityServer4)

I'm using IdentityServer4 to Authenticate my WebApi. I'm looking for events to intercept authentication requests post and prior to authentication.

My startup class is configured this way to handle authentication.

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
    Authority = "http://localhost:5000",
    RequireHttpsMetadata = false,

    ApiName = "api1"
});

I'm looking for an event for post authentication, so that I can create a link from IdentityServer4 Users to local users so I can foreign key there references.

Is there an event or an easy way to plug into Post_Authentication_Requests, and authenication requests in general, I would like to do some additional logging of failed login attempts as well?


Solution

  • Yes, most of the authentication middleware have a way to hook into their respective authentication events. These can be found here. To answer your question thought, there are a few PRE and POST auth event hooks, you will need to pick one that satisfies your needs. example:

    app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
    {
        Authority = "http://localhost:5000",
        RequireHttpsMetadata = false,
    
        ApiName = "api1",
    
        Events = new OpenIdConnectEvents() 
        {
            OnMessageReceived = async context =>
            {
                //example of a "before" event hook
            }
    
            OnTokenValidated = async context =>
            {
                //example of an "after" event hook
                var claimsIdentity = context.Ticket.Principal.Identity as ClaimsIdentity;
                if (claimsIdentity != null)
                {
                    // Get the user's ID
                    string userId = claimsIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
                }
            }
         }
    });
    

    You can also see an example in the samples repo of aspnet/Security here, where they demonstrate how they hijack a failed authentication request to return a 500 (and not the normal 401)