2

Im using role based authorization and it works fine, but for one controller I want a different redirect url than the default one for one controller. My current code:

[Authorize(Roles = nameof(EIdentityType.Support))]
[Route("[controller]")]
public class AdminController : Controller
{
      //CLASS METHODS
}

This redirects the user to

/Account/Login?ReturnUrl=%2Fadmin

However I want the user (for this specific controller so not for other controllers) to be redirected to

/admin/login

I found examples for asp.net mvc-4 which explains how to do it but the example wont work for .net core because in .net core the method HandleUnauthorizedRequest cant be overriden (it does not exist in .net core AuthorizeAttribute).

How can I set a custom redirect URL for a specific controller in .net core when using role based authorization?

Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114
Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169

1 Answers1

2

According to this discussion, authorization redirects are handled by authentication middleware.

For example, if cookie authentication is used you could override CookieAuthenticationEvents.OnRedirectToAccessDenied method to set custom redirect URL depending on request URL:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    Events = new CookieAuthenticationEvents
    {
        OnRedirectToAccessDenied = RedirectToAccessDenied,
        OnRedirectToLogin = ...
        OnRedirectToLogout = ...
        OnRedirectToReturnUrl = ...
    }
});

Implementation (check CookieAuthenticationOptions source code for the default one):

private async Task RedirectToAccessDenied(CookieRedirectContext context)
{
    if (IsAjaxRequest(context.Request))
    {
        //default path
        context.Response.Headers["Location"] = context.RedirectUri;
        context.Response.StatusCode = 403;
    }
    else if (context.Request.Path.Value.Equals("/Foo/Bar"))
    {
        //custom
        context.Response.Redirect("http://google.com");
    }
    else
    {
        //default path
        context.Response.Redirect(context.RedirectUri);
    }
}

private static bool IsAjaxRequest(HttpRequest request)
{
    if (!string.Equals(request.Query["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal))
        return string.Equals(request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal);

    return true;
}
Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114