asp.net - 在基本 Controller 中重写 ASP.NET MVC 中的 OnAuthorization

标签 asp.net asp.net-mvc asp.net-mvc-3

在我的 ASP.NET MVC 应用程序中,我试图确定用户是否有权访问特定 Controller ,并受授权数据注释的限制,如下所示

[Authorize(Roles = "user")]

我正在尝试重写 OnAuthorization 以检查:-

  • 如果请求已通过身份验证(效果很好)
  • 如果用户有权访问所请求的 View (这不起作用)

我的用户角色存储在我创建的 SessionManager 对象中 - SessionManager.ActiveUser.Roles

这是我以伪代码形式获得的内容,但如果有人可以帮助我解决这个问题,我将非常感激。

public class HomeBaseController : Controller
{
    protected override void OnAuthorization(AuthorizationContext context)
    {
        if (context.HttpContext.User.Identity.IsAuthenticated)
        {
            // these values combined are our roleName 

            bool isAuthorised = context.HttpContext.User.IsInRole(context.RequestContext.HttpContext.User.Identity.); 


            if (!context.HttpContext.User.IsInRole(---the roles associated with the requested controller action (e.g. user)---))
            {
                var url = new UrlHelper(context.RequestContext);
                var logonUrl = url.Action("LogOn", "SSO", new { reason = "youAreAuthorisedButNotAllowedToViewThisPage" });
                context.Result = new RedirectResult(logonUrl);

                return;
            } 
        }
    }

最佳答案

根据 ProASP.NET MVC3 Book 重写 OnAuthorization,他们不建议重写它,因为此方法的默认实现可以安全地处理使用 OutputCache Filter 缓存的内容。

如果您正在寻找自定义身份验证(使用表单例份验证)和授权(使用角色提供程序逻辑),那么下面是我如何保护我的应用程序。

编辑:以下逻辑使用内置表单例份验证和角色管理器。用户经过身份验证和授权后,用户身份可用于检查身份验证 (User.Identity.IsAuthenticated) 和角色 User.IsInRole("admin")

在 Web.Config 中:

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="15" slidingExpiration="true" enableCrossAppRedirects="false" protection="All" />
</authentication>
<roleManager enabled="true" defaultProvider="MyRolesProvider" cacheRolesInCookie="true" cookieProtection="All">
  <providers>
    <clear />
    <add name="MyRolesProvider" type="MyApp.Library.CustomRolesProvider" />
  </providers>
</roleManager>

对于角色授权,根据需要扩展 RoleProvider 并覆盖方法。

public class CustomRolesProvider : RoleProvider
{
    public override string[] GetRolesForUser(string username)
    {
       // You need to return string of Roles Here which should match your role names which you plan to use.
       //Some Logic to fetch roles after checking if User is Authenticated...    

        return new string[] { "admin" , "editor" };
    }

    //Rest all of them I have kept not implemented as I did not need them...


}

在你的 Controller 中现在你可以使用这个:

 [Authorize(Roles="Admin")]
    public class AdminController : Controller
    {
    ....

    }

对于身份验证,我已经实现了自定义身份验证检查,但我仍然使用表单例份验证:

//This one calls by Custom Authentication to validate username/password
public ActionResult LogOn(LogOnViewModel model, string returnUrl)
{
    if(Authenticate("test","test"))
    {
     .......
    }
}

public bool Authenticate(string username, string password)
{
   //Authentication Logic and Set the cookie if correct else false.
   //..... your logic....
   //.....

   FormsAuthentication.SetAuthCookie(username, false);
}

关于asp.net - 在基本 Controller 中重写 ASP.NET MVC 中的 OnAuthorization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11223545/

相关文章:

asp.net - 使用 MySql 和 MVC 3 上的成员(member)资格向注册表单添加更多字段

asp.net-mvc-3 - 我可以有使用两个模型的局部 View 吗?

c# - 无法将类型为 'Data' 的对象转换为类型 'System.IConvertible'

c# - 如何使用阅读更多链接限制 GridView 中的标签字符串长度?

asp.net-mvc - 直接在MVC中指定 View 位置是不是效率更高?

javascript - 如何使用 Razor 语法将数组从 ViewBag 转换为 JScript 数组?

asp.net - 在 asp.net 中查看状态与隐藏字段

asp.net - 如何避免在 AutoPostBack 上滚动 UpdatePanel?

c# - ajax中传递参数得到空值

asp.net-mvc - 请推荐为 MVC 网格实现内联编辑的方法?