ASP.NET身份 - 非授权页面

时间:2015-09-30 18:45:45

标签: c# asp.net-mvc asp.net-identity

我试图插入AccountController中的默认switch语句,并将用户重定向到" Not Authorized"页面,如果他们不在管理员角色。

默认代码

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

如果我从帐户/登录开始,这一切都正常,但如果我的网址附有ReturnURL,我就无法将其重定向到“未授权”页面。

例如,我有一个看起来像这样的Admin控制器。

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

如果我尝试直接转到该管理员页面,则在未登录时,我的页面将重定向到帐户/登录,并且网址将如下所示http://localhost:51250/Account/Login?ReturnUrl=%2FAdmin 这是在登录赢得工作期间重定向到NotAuthorized的位置。如果我的网址如此http://localhost:51250/Account/Login,则重定向到NotAuthorized 工作。

在浏览我的switch语句时应忽略返回网址,我不会看到我错过的内容。

1 个答案:

答案 0 :(得分:2)

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

return RedirectToAction("NotAuthorized");

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

[AllowAnonymous]
public ActionResult NotAuthorized()
{
    return View();
}
相关问题