【问题标题】:Customise Behaviour On Authorize Failed自定义授权失败时的行为
【发布时间】:2016-03-19 05:12:47
【问题描述】:
通过在我的控制器中使用[Authorize(Roles = "Admin")] 标签,我已经成功地在 MVC 应用程序中实现了基于组的授权。
但是,当用户请求他们无权查看的页面时,默认行为是将他们重定向到登录页面。这远非直观,并且会在反复尝试登录的用户中造成过多的混淆。
相反,我想显示一个自定义屏幕,或者至少在登录屏幕上显示一条消息,说明他们已经登录,但权限不足。
存在User.Identity.IsAuthenticated 标记,可以在基本逻辑中使用,但似乎没有类似的 IsAuthorised 标记。
如何实现这种行为?
【问题讨论】:
标签:
asp.net-mvc-4
authorization
user-roles
【解决方案1】:
我相信您已经部分解决了您的问题。这是因为当授权失败时,用户将被重定向到登录页面。在显示登录视图之前验证用户是否已通过身份验证。如果他们通过身份验证,则将它们重定向到适当的页面。如果用户通过身份验证并且 cookie 尚未过期,则下面的代码 sn-p 将不会显示登录视图。它们将被重定向到“DashboardOrSomeOtherView.cshtml”
[HttpGet]
public ActionResult Login(string returnUrl)
{
// Before showing login view check if user is authenticated.
// If they are redirect to suitable page,
// and print appropriate message
if (ControllerContext.HttpContext.User.Identity.IsAuthenticated)
{
// You can even use TempData as additionally, to hold data here and check in
//the view you redirect to if it is not null and is true ,
// then they are authenticated and show some message,
// e.g. You have been redirected here because you do not
// have authorization to view previous page.
TempData["UserAlreadyAuthicated"] = true;
return RedirectToAction("DashboardOrSomeOtherView");
}
// If they are not authenticated , show them login view
return View();
}
在 DashboardOrSomeOtherView 中
<div>
<h1>DashboardOrSomeOtherView</h1>
@{
if(TempData["UserAlreadyAuthicated"] != null && TempData["UserAlreadyAuthicated"].ToString().ToLower() == "true")
<div>You have been redirected here because of inadequate authorization</div>
}
</div>