如何在Blazor Web Assembly应用中返回403 Forbidden而不是重定向? [英] How can I return 403 Forbidden instead redirect in Blazor Web Assembly app?

查看:183
本文介绍了如何在Blazor Web Assembly应用中返回403 Forbidden而不是重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个Blazor WebAssembly-App,可与ASP.NET Core API控制器(V3.1)一起使用.与我们的Api控制器中的[Authorize]属性配合使用的身份验证Cookie:

We have an Blazor WebAssembly-App which works with an ASP.NET Core API-Controller (V3.1). The Authentication Cookie which works well with [Authorize] attribute in our Api-Controller:

namespace BlazorWebAssemblyApp.Server.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class ClientsController : ControllerBase
    {          
        private const string AuthSchemes = CookieAuthenticationDefaults.AuthenticationScheme;

        [HttpGet("search")]
        [Authorize(AuthenticationSchemes = AuthSchemes)]
        public ActionResult<List<Shared.Client>> Search(Shared.Client.SearchProperty pProperty, string pText)
        {
            // [...]
        }
    }
}

我们正在使用

We are using the solution described here to return an HTTP-Status Code 403 Forbidden instead routing to the login page.

namespace BlazorWebAssemblyApp.Server
{
    public class Startup
    {
        // [...]

        public void ConfigureServices(IServiceCollection services)
        {
            // [...]
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options => {
                options.Events.OnRedirectToAccessDenied = context => {
                    context.Response.StatusCode = 403;
                    return Task.CompletedTask;
                };
            });
        }
    }
}

但是解决方案不起作用.该应用仍会重定向到默认路径/Account/Login:

But the Solution is not working. The app still redirects to default path /Account/Login:

如何在Blazor Web Assembly应用中返回http状态代码403 Forbidden而不是重定向?

How can I return the http-status code 403 Forbidden instead redirect in Blazor Web Assembly app?

推荐答案

只需添加OnRedirectToLogin即可

options.Events.OnRedirectToLogin = context =>
{
    context.Response.StatusCode = 401; // or 403 if you want
    return Task.CompletedTask;
};

这篇关于如何在Blazor Web Assembly应用中返回403 Forbidden而不是重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆