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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With