UseStatusCodePagesWithReExecute is not working for forbidden (403)

╄→尐↘猪︶ㄣ 提交于 2020-05-23 10:06:25

问题


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

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

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:


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;
});


来源:https://stackoverflow.com/questions/56868673/usestatuscodepageswithreexecute-is-not-working-for-forbidden-403

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!