在基本控制器覆盖OnAuthorization在ASP.NET MVC [英] Overriding OnAuthorization in ASP.NET MVC in base controller

查看:808
本文介绍了在基本控制器覆盖OnAuthorization在ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET MVC应用程序,我想弄清楚用户是否有权访问特定的控制器,由授权数据注解如下限制

  [授权(角色=用户)]

我试图重写OnAuthorization以检查: -


  • 如果该请求被认证(这伟大工程)

  • 如果用户被授权访问请求的观点(不工作)

我的用户角色都存储在我创建了一个对象是SessionManager - SessionManager.ActiveUser.Roles

下面是我在伪code的形式,但如果有人可以帮助我得到这个权利,我真的AP preciate它。

 公共类HomeBaseController:控制器
{
    保护覆盖无效OnAuthorization(AuthorizationContext上下文)
    {
        如果(context.HttpContext.User.Identity.IsAuthenticated)
        {
            //这些值结合起来,是我们的角色名            布尔isAuthorised = context.HttpContext.User.IsInRole(context.RequestContext.HttpContext.User.Identity);
            如果(!context.HttpContext.User.IsInRole(---与所请求的控制器动作(例如,用户)---)关联的角色)
            {
                VAR URL =新UrlHelper(context.RequestContext);
                VAR logonUrl = url.Action(登录,SSO,新{原因=youAreAuthorisedButNotAllowedToViewThisPage});
                context.Result =新RedirectResult(logonUrl);                返回;
            }
        }
    }


解决方案

至于根据ProASP.NET MVC3书,他们不建议重写它,因为此方法的默认实现使用的OutputCache过滤器安全处理的内容缓存覆盖OnAuthorization。

如果您正在寻找自定义验证(使用窗体身份验证)和授权(使用角色提供程序逻辑然后在下面就是我如何保护我的应用程序。

编辑:下面的逻辑使用内置的表单认证和角色管理器。一旦用户通过验证,并授权用户身份可以用来检查这两个认证(User.Identity.IsAuthenticated)和角色User.IsInRole(管理员)

在Web.Config中:

 <身份验证模式=表格>
  <形式loginUrl =〜/帐号/登录超时=15slidingExpiration =真enableCrossAp predirects =false的保护=全部/>
< /认证>
< roleManager启用=真正的defaultProvider =MyRolesProvidercacheRolesInCookie =真cookieProtection =所有>
  <供应商>
    <清/>
    <添加名称=MyRolesProviderTYPE =MyApp.Library.CustomRolesProvider/>
  < /供应商>
< / roleManager>

有关角色授权扩展RoleProvider,并根据需要覆盖的方法。

 公共类CustomRolesProvider:RoleProvider
{
    公共重写字符串[] GetRolesForUser(用户名字符串)
    {
       //你需要返回角色串在这里应符合您计划使用您的角色名称。
       //一些逻辑来当用户通过验证后,确认取出的角色...        返回新的字符串[] {管理员,编辑};
    }    //其余所有的人我一直没有实现,因为我并不需要他们。
}

在你的控制器,现在你可以使用这个:

  [授权(角色=管理员)]
    公共类AdminController:控制器
    {
    ....    }

有关身份验证我已经实现了我的自定义身份验证检查,但我仍然使用窗体身份验证:

通过自定义身份验证

  //这一次调用来验证用户名/密码
公众的ActionResult登录(LogOnViewModel型号,串RETURNURL)
{
    如果(认证(测试,测试))
    {
     .......
    }
}公共BOOL身份验证(用户名字符串,字符串密码)
{
   //认证逻辑,如果正确否则为false设置的cookie。
   // .....你的逻辑....
   // .....   FormsAuthentication.SetAuthCookie(用户名,虚假);
}

In my ASP.NET MVC application, I'm trying to figure out whether the user has access to a particular controller, restricted by the authorize data annotation as follows

[Authorize(Roles = "user")]

I'm attempting to override OnAuthorization in order to check:-

  • If the request is authenticated (which works great)
  • If the user is authorised to access the requested view (which doesn't work)

My user roles are stored in a SessionManager object I've created - SessionManager.ActiveUser.Roles

Here's what I have in the form of pseudo-code but if anybody could help me get this right, I'd really appreciate it.

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

解决方案

As far as overriding OnAuthorization according to ProASP.NET MVC3 Book they do not recommend overriding it since the default implementation of this method securely handles content cached using OutputCache Filter.

If you are looking for Custom Authentication (using Forms Auth) and Authorization (Using Role provider logic then below is how I secured my application.

EDIT: The following logic uses in-built forms authentication and roles manager. Once user is authenticated and authorized the User Identity can be used to check both the authentication (User.Identity.IsAuthenticated) and the roles User.IsInRole("admin")

In 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>

For Role Authorization Extend RoleProvider and override methods as required.

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...


}

In Your controller Now you can use this:

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

    }

For Authentication I have implemented my custom Authentication Check but I still use Forms Authentication:

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

这篇关于在基本控制器覆盖OnAuthorization在ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆