我想在我的一个视图中添加集成的Windows安全性,这可能吗?
在网络表单上,我只是在IIS中找到该文件并在那里添加文件安全功能,obv MVC是非文件的,这似乎不起作用.
该网站正在使用Forms Auth - 尝试使其适用于MVC http://beensoft.blogspot.com/2008/06/mixing-forms-and-windows-authentication.html
谢谢
您可以在名为AuthorizeAttribute的Action方法上使用安全属性.
例如,
[Authorize(Roles = "Domain Users")]
public ActionResult Create(FormCollection collection)
Run Code Online (Sandbox Code Playgroud)
为了限制对链接等的访问,甚至将它们隐藏在用户之外,我们实现了一个名为SecurityTrimmedActionLink的扩展方法,我们主要通过http://www.inq.me/post/ASPNet-MVC-Extension-method-修改/借用它. to-create-a-Security-Aware-HtmlActionLink.aspx.
public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action, object routeValues)
{
if (IsAccessibleToUser(action, htmlHelper.ViewContext.Controller))
{
return htmlHelper.ActionLink(linkText, action, routeValues);
}
return string.Empty;
}
public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action)
{
return SecurityTrimmedActionLink(htmlHelper, linkText, action, null);
}
private static bool IsAccessibleToUser(string action, ControllerBase controller)
{
ArrayList controllerAttributes = new ArrayList(controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true));
ArrayList actionAttributes = new ArrayList();
MethodInfo[] methods = controller.GetType().GetMethods();
foreach (MethodInfo method in methods)
{
object[] attributes = method.GetCustomAttributes(typeof(ActionNameAttribute), true);
if ((attributes.Length == 0 && method.Name == action) || (attributes.Length > 0 && ((ActionNameAttribute)attributes[0]).Name == action))
{
actionAttributes.AddRange(method.GetCustomAttributes(typeof(AuthorizeAttribute), true));
}
}
if (controllerAttributes.Count == 0 && actionAttributes.Count == 0)
return true;
IPrincipal principal = HttpContext.Current.User;
string roles = "";
string users = "";
if (controllerAttributes.Count > 0)
{
AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (actionAttributes.Count > 0)
{
AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated)
return true;
string[] roleArray = roles.Split(',');
string[] usersArray = users.Split(',');
foreach (string role in roleArray)
{
if (role == "*" || principal.IsInRole(role))
return true;
}
foreach (string user in usersArray)
{
if (user == "*" || (principal.Identity.Name.Equals(user, StringComparison.InvariantCultureIgnoreCase)))
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
431 次 |
| 最近记录: |