UseStatusCodePagesWithReExecute is not working for forbidden (403)

Viewed 984

When I specify 404 as a http result code, UseStatusCodePagesWithReExecute is working like expected.

enter image description here

When I specify 403 as a http result code, UseStatusCodePagesWithReExecute is not working like expected. Somehow it works like I have specified UseStatusCodePagesWithRedirects.

enter image description here

I need the behaviour of UseStatusCodePagesWithReExecute for all status codes in range of 400-600, including 403.

The configuration code:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    //...
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Cookie.HttpOnly = true;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                options.Cookie.SameSite = SameSiteMode.None;
                options.AccessDeniedPath = new PathString("/error/403/");
                options.LoginPath = "/account/signinrouter/";
            });
    //...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
    //...
    app.UseStatusCodePagesWithReExecute("/error/{0}");
    //...
}

The action code:

public IActionResult NotFound()
{
    return base.NotFound();
}

public IActionResult Forbidden()
{
    return base.Forbid();
}
1 Answers

Figured it out, thanks to @Kirk

Adding this code to AddCookie does the trick.

options.Events.OnRedirectToAccessDenied = context =>
{
    context.Response.StatusCode = 403;

    return Task.CompletedTask;
};

This is the original event handler method, I don't care the Location header, so I have omitted the related code, you may not want to.

public Func<RedirectContext<CookieAuthenticationOptions>, Task> OnRedirectToAccessDenied { get; set; } = (Func<RedirectContext<CookieAuthenticationOptions>, Task>) (context =>
{
    if (CookieAuthenticationEvents.IsAjaxRequest(context.Request))
    {
    context.Response.Headers["Location"] = (StringValues) context.RedirectUri;
    context.Response.StatusCode = 403;
    }
    else
    context.Response.Redirect(context.RedirectUri);
    return Task.CompletedTask;
});
Related