Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper Way to Redirect to controller action/view from .net core 2.1 middleware

I have a .NET Core 2.1/Angular 6 application, I am trying to redirect users to a static view if they are not part of a security group. I just keep getting "Error too many redirects" when running the app.

I have a securityMiddleWare that is called from Startup.cs

public class ADAuthMiddleware
{

    RequestDelegate next;

    public ADAuthMiddleware(RequestDelegate next)
    {

        this.next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        //check if user belongs to AD group or not
        var isAuthorized = httpContext.User.IsInRole("app.users.foo");


        // Return error if the current user is not authorized
        if (!isAuthorized)
        {
            httpContext.Response.StatusCode = 403;
            return;
        }

        // Jump to the next middleware if the user is authorized
        await next(httpContext);
    }

}

right now I have it set to return the response of 403, this just generates the standard ugly "unauthorized page" so i wanted a cleaner way to send users to a new view where they can get instructions on getting access... access denied

I've tried httpContext.Response.Redirect(/controller/action) with no luck. this works fine on the full .NET framework with MVC. i've found issues so far with .NET Core.. also maybe because it's running inside a Task instead of IActionResult?

like image 767
Flightdoc5242 Avatar asked Oct 22 '25 01:10

Flightdoc5242


1 Answers

You need to add some logic in your middleware to ensure you don't attempt to authenticate the user again after redirecting them.

Else you'll end up in a loop of redirecting, authenticating, then redirecting because they're unauthenticated.

In the Configure() method of Startup.cs you can conditionally apply your authentication, e.g.

app.UseWhen(ShouldAuthenticate, appBuilder =>
    {
        appBuilder.UseMiddleware<ADAuthMiddleware>();
    });

And define ShouldAuthenticate as:

private static bool ShouldAuthenticate(HttpContext context)
{
    var path = context.Request.Path;
    return !context.Request.Path.StartsWithSegments("/staticpage");
}

For redirection, you can do so in the same Configure() method, e.g.

app.Use(async (context, next) =>
{
    await next.Invoke();
    if (context.Response.StatusCode == 401)
    {
        context.Response.Redirect("/redirectpage/"); 
    }
});

Note that this is a simple way of achieving it and there are more "Core" ways of doing this using Identity services etc

like image 76
Widor Avatar answered Oct 24 '25 14:10

Widor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!