将所有未经授权的用户重定向到未经授权的视图

redirect all unauthorized users to unauthorized view

我们构建了一个目前尚未实现身份的应用程序。

作为临时快速修复,我想将所有未经授权的用户重定向到未经授权的页面。

它适用于 HomeController,但我想实现一个中间件或其他东西,以便为所有控制器全局检查它

[Authorize]
public class HomeController : Controller
{
    private readonly IUserResolverService _userService;

    public HomeController(IUserResolverService userService)
    {
        _userService = userService;
    }

    public IActionResult Index()
    {
        if (_userService.GetCurrentUser() == null) // unauthorized user
            return View("Unauthorized");

        return View();
    }

    public IActionResult Error()
    {
        return View();
    }
}

丑陋,但作为快速修复,我在 _Layout.cshtml 中设法重定向到 Home 控制器的 Index 操作,如下所示:

@inject IUserResolverService userService
@{
    var currentUser = userService.GetCurrentUser();
    if (currentUser == null) {
        Context.Response.Redirect("/");
        return;
    }