ASP.NET 身份 - 未经授权的页面

ASP.NET Identity - Not Authorized Page

我正在尝试插入 AccountController 中的默认 switch 语句,并将用户重定向到 "Not Authorized" 页面(如果他们不属于 Admin 角色)。

默认代码

// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);
        case SignInStatus.LockedOut:
            return View("Lockout");
        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl });
        case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
    }
}

这是我要添加到 switch 语句的 SignInStatus.Success 案例中的内容

switch (result)
    {
        case SignInStatus.Success:
        //After successful login - check if the user is not in the admin role
            if (!UserManager.IsInRole(user.Id, "Admin"))
            {
                //Send to the Not Authorized page
                return View("NotAuthorized");
            }
            //Successful login with admin role
            else
            {
                //Return to where they came from 
                return RedirectToLocal(returnUrl);
            }
        case SignInStatus.LockedOut:
            //Lockout settings in IdentityConfig.cs
            return View("Lockout");
        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl });
        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }

如果我从 Account/Login 开始一切正常,但如果我的 URL 附有 ReturnURL,我无法将其重定向到 Not Authorized页。

例如,我有一个如下所示的管理控制器。

[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
    // GET: Admin
    public ActionResult Index()
    {
        return View();
    }
}

如果我尝试直接进入该管理页面,当未登录时,我的页面将重定向到 Account/Login 并且 URL 将如下所示 http://localhost:51250/Account/Login?ReturnUrl=%2FAdmin 这是在登录期间重定向到 NotAuthorized 不会 工作的地方。如果我的 URL 看起来像这样 http://localhost:51250/Account/Login 重定向到 NotAuthorized 工作。

在执行我的 switch 语句时应该忽略 return URL,我没有看到我遗漏了什么。

您没有进行重定向。您告诉它为登录操作使用 NotAuthorized 视图。要进行重定向,请使用 RedirectToAction()。

return RedirectToAction("NotAuthorized");

如果您还没有 NotAuthorized 操作,则需要在您的帐户控制器中添加一个。

[AllowAnonymous]
public ActionResult NotAuthorized()
{
    return View();
}