Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to handle Post Authenticate in Asp.Net Core

I'm ready to use Asp.Net core, but here's what I am doing. In MVC 5, I have an Http module that is handling the PostAuthenticate event in order to create the claim where I am doing some stuff to determine roles for the user. I see no way to do this same thing in Core. Note that this is using Windows Authentication so there is no login method to handle.

From the current httpModule that hooks up to the PostAuthenticate because I want to initialize some things for the user.
context.PostAuthenticateRequest += Context_PostAuthenticateRequest;

Note that httpModules no longer exist with Core and that is being moved to middleware.. I don't see how to tap into that event from there though.

like image 821
user3720939 Avatar asked Oct 30 '22 05:10

user3720939


1 Answers

I just did this for the first time today. Two basic steps here.

First: Create a class that implements the IClaimsTransformer interface.

public class MyTransformer : IClaimsTransformer
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context )
    {
        //don't run if user isn't logged in 
        if(context.Principal.Identity.IsAuthenticated)
        {
           ((ClaimsIdentity)context.Principal.Identity)?.AddClaims(...);
        }
    }
    return Task.FromResult(context.Principal);
}

Second: Add this line to Startup.cs in

public void Configure(IApplicationBuilder app, ..., ...)
{
    //app.Use...Authentication stuff above, for example
    app.UseOpenIdConnectAuthentication( new OpenIdOptions
    {
        //or however you like to do this. 
    });

    app.UseClaimsTransformation(o => new MyTransformer().TransformAsync(o));
    //UseMvc below
    app.UseMvc(...);
}

Keep in mind that TransformAsync is going to run on every request, so you might want to look into using sessions or caching if you're hitting a database with it.

like image 57
stiljack Avatar answered Dec 27 '22 07:12

stiljack