ASP.Net MVC的安全工具包

时间:2016-04-08 17:17:18

标签: c# asp.net-mvc security nhibernate permissions

我实际上用NHibernate开发了一个带ASP.Net MVC的网站 我需要管理组,页面和其他一些事情的权限 我想要我的角色,权限,操作,组以及我的数据库中的所有内容。

和旧的post一样,我想知道Ayende Rhino Security工具包是否仍然相关,或者是否还有其他相关的通用工具包?

3 个答案:

答案 0 :(得分:0)

对于我的新项目,我使用过身份系统

http://www.asp.net/identity

ASP.NET Identity系统旨在取代以前的ASP.NET成员资格和简单成员资格系统。它包括配置文件支持,OAuth集成,与OWIN一起使用,并包含在Visual Studio 2013附带的ASP.NET模板中。

特别是本教程第一次帮助了我很多次

http://benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-1

答案 1 :(得分:0)

您也可以考虑MembershipReboot。据我所知,它仍然超越了Asp.Net Identity,尽管它最初是为了克服会员资格的缺点。

关于Rhino Security toolkit,我不知道它处于哪种状态。

答案 2 :(得分:0)

以下是我所做的一个例子

第1步 - 为用户创建声明

var identity = new ClaimsIdentity(
    new[] {
            new Claim(ClaimTypes.Name, usr.Name),
            new Claim(ClaimTypes.Email, usr.Email),
            new Claim(ClaimTypes.Role, usr.Roles.FirstOrDefault().Role),
            new Claim("StuffXId", usr.StuffXId + ""),
            new Claim("StuffYId", usr.StuffYId + "")

    }
    , "BMMC"//"ApplicationCookie"
);

foreach(AccessLevels x in usr.AccessLevels)
    identity.AddClaim(new Claim("AccessLevel", x.Access));

第2步 - 我创建了我的班级BMClaimsAuthorize

public class BMClaimsAuthorize : AuthorizeAttribute
{
    public string ClaimType { get; set; }
    public string Value { get; set; }

    public BMClaimsAuthorize() { }

    public BMClaimsAuthorize(string ClaimType, string Value)
    {
        this.ClaimType = ClaimType;
        this.Value = Value;
    }

    protected override bool AuthorizeCore(HttpContextBase context)
    {
        return context.User.Identity.IsAuthenticated
            && context.User.Identity is ClaimsIdentity
            && ((ClaimsIdentity)context.User.Identity).HasClaim(x =>
                x.Type == ClaimType && x.Value == Value);

    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (filterContext.Result is HttpUnauthorizedResult)
            filterContext.Result = new RedirectResult("~/Account/DeniedAccess");

    }

}

3 - 使用peject.BMTools(导入我的库)

[BMClaimsAuthorize("AccessLevel", "General")]
public ActionResult Index()
{
    ViewBag.Name = CurrentUser.Name;
    ViewBag.Email = CurrentUser.Email;
    ViewBag.StuffX = CurrentUser.ValueOf("StuffXId");
    return View();
}

我创建了自己的cotroller类(继承自控制器),可以帮助我轻松获得用户声明

CurrentUser.Name

但那是另一个主题..

这是我的实际代码,我有2个表,其中用户被映射到角色和访问级别

角色只告诉他们是否是管理员(保留为表而不是用户字段以防我以后需要多个角色),它们位于控制器clases的顶部,只有adminds可以访问。

AccessLevel告诉其他所有内容(它们按方法过滤)。如果您需要更复杂的内容,可以添加更多声明(作为我的AccessLevel声明)并编辑BMClaimsAuthorize和AuthorizeCore方法以满足您的条件。

例如,让它接受一个字符串数组,所以你发送这样的东西

[BMClaimsAuthorize("AccessLevel", {"General","Admin","other"...})]

希望这有帮助!