加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

在基本控制器中覆盖ASP.NET MVC中的OnAuthorization

发布时间:2020-12-16 07:28:17 所属栏目:asp.Net 来源:网络整理
导读:在我的ASP.NET MVC应用程序中,我试图弄清楚用户是否可以访问特定的控制器,受授权数据注释的限制如下 [Authorize(Roles = "user")] 我试图覆盖OnAuthorization以检查: – 如果请求已通过身份验证(效果很好) 如果用户被授权访问所请求的视图(这不起作用) 我的
在我的ASP.NET MVC应用程序中,我试图弄清楚用户是否可以访问特定的控制器,受授权数据注释的限制如下

[Authorize(Roles = "user")]

我试图覆盖OnAuthorization以检查: –

>如果请求已通过身份验证(效果很好)
>如果用户被授权访问所请求的视图(这不起作用)

我的用户角色存储在我创建的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缓存的内容.

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

编辑:以下逻辑使用内置窗体身份验证和角色管理器.用户通过身份验证和授权后,可以使用用户身份检查身份验证(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...


}

在您的控制器中现在您可以使用此:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读