c# MVC中權限處理

1.建立SecurityActionAttribute 類

代碼如下

View Code
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class SecurityActionAttribute : ActionFilterAttribute
{
private string permssionSet = "Default";
private string title = "";
private string description = "";
//private string redirectToController = "Security";
private string redirectToAction = "";
private bool throwOnDeny = false;
private string resBaseName = "perms";
private string titleResName = "";
private string descResName = "";
private string permssionSetResName = "";

public string PermssionSetResName
{
get { return permssionSetResName; }
set { permssionSetResName = value; }
}

public string DescResName
{
get { return descResName; }
set { descResName = value; }
}

public string TitleResName
{
get { return titleResName; }
set { titleResName = value; }
}

public string ResBaseName
{
get { return resBaseName; }
set { resBaseName = value; }
}

public bool ThrowOnDeny
{
get { return throwOnDeny; }
set { throwOnDeny = value; }
}

/// <summary>
/// Gets/Sets the Action to redirect when authorize fail
/// </summary>
public string RedirectToAction
{
get
{
return redirectToAction;
}
set { redirectToAction = value; }
}

/// <summary>
/// Init the SecurityActionAccribute class
/// </summary>
/// <param name="permissionSetName">Set the PermissionSetName which this Action belongs to.</param>
/// <param name="permissionTitle">Set the PermissionTitle of this Action</param>
public SecurityActionAttribute(string permissionSetName, string permissionTitle)
{
permssionSet = permissionSetName;
title = permissionTitle;
}

/// <summary>
/// Init the SecurityActionAccribute class
/// </summary>
/// <param name="permissionTitle">Set the PermissionTitle of this Action</param>
public SecurityActionAttribute(string permissionTitle)
{
title = permissionTitle;
}

public SecurityActionAttribute(string permissionSetName, string permissionTitle, string permissionDescription)
{
permssionSet = permissionSetName;
title = permissionTitle;
description = permissionDescription;
}

/// <summary>
/// Get/Sets the Description of the Permission for this Action
/// </summary>
public string Description
{
get { return description; }
set { description = value; }
}

/// <summary>
/// Gets/Sets the Title text of the Action
/// </summary>
public string Title
{
get { return title; }
set { title = value; }
}

/// <summary>
/// Gets/Sets the PermissionSet name which the security action belongs to
/// </summary>
///<remark>
/// If the permission name is not exists Portal will add a new one
///</remark>
public string PermssionSet
{
get { return permssionSet; }
set { permssionSet = value; }
}

[Dependency]
public virtual WebSiteContext Context { get; set; }

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.IsWebOwner() || Context.IsAuthorized(filterContext.Controller.GetType(), filterContext.ActionDescriptor.ActionName))
{
//要对SiteMapAttribute进行控制
if (filterContext.ActionDescriptor.IsDefined(typeof(SiteControlPanelAttribute), false))
{
var cpAttrs = (SiteControlPanelAttribute)filterContext.ActionDescriptor.GetCustomAttributes(typeof(SiteControlPanelAttribute), false).First();

if (Context.Web!=null && !Context.Web.IsRoot)
{
if (cpAttrs.ShowInTopSiteOnly)
{
filterContext.Result = new PageNotFoundResult();
}
else
{
var isAuthorized = Context.IsAuthorized(filterContext.Controller.GetType(), filterContext.ActionDescriptor.ActionName);

if (!isAuthorized)
{
if (Context.Web.Type == (int)WebTypes.Personal)
{
if (!filterContext.ActionDescriptor.IsDefined(typeof(MyControlPanelAttribute), false))
filterContext.Result = new PageNotFoundResult();
}
}
}
}
}
base.OnActionExecuting(filterContext);
}
else
{
if (throwOnDeny)
{
throw new AccessDenyException();
}
else
{
filterContext.Result = new HttpUnauthorizedResult();
base.OnActionExecuting(filterContext);
}
}
}

}

2.在collection上應用SecurityAction

代碼如下:

      [SecurityAction("Management base", "View log", "Allows users can view or clear the system log.",
            PermssionSetResName = "SA_Managementbase",
            TitleResName = "SA_ViewLog",
            DescResName = "SA_ViewLogDesc"
            )]
        public ActionResult Index(QueryParams query)
        {
            var total = 0;
            var logs = _logRepository.All(out total, query.Index - 1, query.Size).ToList();
            return View(new ModelWrapper()
            {
                Total = total,
                Model = logs
            });
        }
3.程序啟動,讀取所有權限,寫入 db中,如果權限表示空的

代碼如下:

View Code
 public void Init()
{
string[] files = Directory.GetFiles(_targetPath, "*.dll");
foreach (string file in files)
{
try
{
//When using LoadFile will cause could not get CustomAttributes!
Assembly assembly = Assembly.LoadFrom(file);
AssemblyName asmname = assembly.GetName();
Type[] types = assembly.GetTypes();
var controllers = from c in types
where c.BaseType == typeof(Controller)
select c;

Dictionary<string, string> added = new Dictionary<string, string>();

foreach (Type controller in controllers)
{
var methods = controller.GetMethods(BindingFlags.Public | BindingFlags.Instance);
var actions = from MethodInfo method in methods
where (method.GetCustomAttributes(typeof(SecurityActionAttribute), true).Length > 0)
select method;

foreach (MethodInfo action in actions)
{
SecurityActionAttribute attr = (SecurityActionAttribute)Attribute.GetCustomAttribute(action, typeof(SecurityActionAttribute));

var instance = context.Permissions.Filter(p => (p.Action.Equals(action.Name, StringComparison.OrdinalIgnoreCase)) &&
(p.Assembly.Equals(asmname.Name, StringComparison.OrdinalIgnoreCase)) &&
(p.Controller.Equals(controller.FullName, StringComparison.OrdinalIgnoreCase)) &&
(p.Title.Equals(attr.Title, StringComparison.OrdinalIgnoreCase)));

if (instance.Count() > 0)
continue;

string _key = asmname.Name + "_" + controller.FullName + "_" + action.Name;
if (added.ContainsKey(_key))
{
if (added[_key] == attr.Title)
continue;
}
else
added.Add(_key, attr.Title);

Permission permission = new Permission()
{
Action = action.Name,
Assembly = asmname.Name,
Controller = controller.FullName,
Title = attr.Title,
Description = attr.Description
};

PermissionSet pset = null;
if (!string.IsNullOrEmpty(attr.PermssionSet))
pset = context.PermissionSets.Find(p => p.Name.Equals(attr.PermssionSet, StringComparison.OrdinalIgnoreCase));

//var _updateCount = 0;

if (pset == null)
{
pset = new PermissionSet();
pset.Name = attr.PermssionSet;
pset.ResbaseName = attr.ResBaseName;
pset.TitleResName = attr.PermssionSetResName;
pset = context.PermissionSets.Create(pset);
//_updateCount=context.SaveChanges();
}

permission.PermissionSet = pset;
context.Permissions.Create(permission);
context.SaveChanges();
}
}
}
catch (Exception e) { continue; }
}

RemoveUsingPermissions();
}

4.得到當前用戶的所有權限

代碼如下:

        public IEnumerable<Permission> Permissions
{
get
{
if (IsNotInstalled) return null;

if ((rolesPermissions == null) && (HttpContext.Request.IsAuthenticated))
{
rolesPermissions = DataContext.Permissions.GetUserPermissions(User.Identity.Name);
if ((rolesPermissions != null) && (rolesPermissions.Count() > 0))
permHashValues = rolesPermissions.Select(p => (p.Controller + "." + p.Action).ToLower().GetHashCode()).ToArray();
}
return rolesPermissions;
}
}




posted @ 2012-03-11 17:32  無限遐想  阅读(2401)  评论(0编辑  收藏  举报