Need for Post Authenticate Processing in Core Asp.Net

I am ready to use the Asp.Net core, but here is what I am doing. In MVC 5, I have an Http module that handles the PostAuthenticate event to create an application where I do some things to define roles for the user. I see no way to do the same in Core. Please note that this is used for Windows authentication, so there is no way to log in.

From the current httpModule, which connects to PostAuthenticate, because I want to initialize some things for the user.
context.PostAuthenticateRequest + = Context_PostAuthenticateRequest;

Please note that httpModules no longer exists with Core and is ported to middleware. I do not see how to use this event from there.

+3
source share
2 answers

I just did it for the first time today. There are two main 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 will run on every request, so you may need to examine sessions or caching if you hit the database with it.

+2
source

Windows (IIS HttpSys/WebListener) . PostAuthenticateRequest. HttpContext.User, .

0

Source: https://habr.com/ru/post/1681216/


All Articles