Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to request authentication from custom middleware in ASP.NET Core 2.0

I have two custom ASP.NET Core middlewares: one for authentication (that registers its own authentication scheme) and a second one for some business work.

How can I use the authentication middleware in another middleware? I can use authentication easily in an MVC like that:

 services.AddMvc(config =>
 {
     var policy = new AuthorizationPolicyBuilder()
                      .RequireAuthenticatedUser()
                      .Build();
     config.Filters.Add(new AuthorizeFilter(policy));
 });

I can also provide my own AuthenticationSchemeProvider to use different authentication schemes based on the requested URL. But the authentication middleware only runs for MVC controllers. I want it to run also before my custom middleware runs. Is it possible to do that?

like image 252
Rython Avatar asked May 11 '18 10:05

Rython


People also ask

Where do I register middleware in .NET Core?

Search for word "middleware" in the top right search box as shown below. Select Middleware Class item and give it a name and click on Add button. This will add a new class for the middleware with extension method as shown below.

How do I use middleware in NET Core?

Middleware are software components that are assembled into an application pipeline to handle requests and responses. Each component chooses whether to pass the request on to the next component in the pipeline, and can perform certain actions before and after the next component is invoked in the pipeline.


1 Answers

In custom middleware method Invoke() call ChallengeAsync() if user is not authenticated:

public async Task Invoke(HttpContext httpContext, IServiceProvider serviceProvider)
{
    if (!httpContext.User.Identity.IsAuthenticated)
    {
        await httpContext.ChallengeAsync();
    }
    else { /* logic here */ }
}

NuGet package Microsoft.AspNetCore.Authentication.Abstractions has to be added.

Above code will run the default authentication service to authenticate user. If the default one is your custom authentication middleware, then it will be called.

like image 97
Rython Avatar answered Oct 05 '22 12:10

Rython