在授权失败时自定义行为

时间:2015-12-13 18:45:49

标签: asp.net-mvc-4 authorization user-roles

我已使用控制器中的[Authorize(Roles = "Admin")]标记在MVC应用程序中成功实现了基于组的授权。

但是,当用户请求他们无权查看的页面时,默认行为是将它们重定向到登录页面。这远非直观,并且会在反复尝试登录的用户之间造成太多混淆。

相反,我希望显示一个自定义屏幕,或者至少在登录屏幕上显示一条消息,说明他们已经登录,但权限不足。

存在User.Identity.IsAuthenticated标记,可以在基本逻辑中使用,但似乎没有类似的IsAuthorised标记。

如何实施此行为?

1 个答案:

答案 0 :(得分:0)

我相信你已经部分解决了你的问题。这是因为当授权失败时,用户将被重定向到登录页面。在显示登录视图之前验证用户是否已通过身份验证。如果他们经过身份验证,则将其重定向到相应的页面。如果用户已通过身份验证且cookie未过期,则下面的代码段将不会显示登录视图。它们将被重定向到" 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>
相关问题