asp.net mvc的[授权()]属性混合组和用户 [英] asp.net mvc [Authorize()] attribute for mixed group and user
问题描述
我使用ASP.NET MVC 1.1 Windows身份验证。我想只授权一个组,我自己的成员。我不是组的成员,就不需要成为这个组的成员。我得到的Windows登录/密码提示我每次访问Web应用程序的URL时。 HomeController的有
I am using ASP.NET MVC 1.1 with Windows authentication. I trying to only authorize members of a group and myself. I am not a member of the group and would not need to be a member of this group. I am getting windows login/password prompt every time I access the URL of the web app. The HomeController has
[HandleError]
[Authorize(Roles=@"MyDomain\\company.security.group.name")]
[Authorize(Users=@"MyDoamin\\MyName")]
[OutputCache(Duration=86400,VaryByParam="PageIndex")]
public class HomeController : Controller
我如何使这样的授权? Web应用程序是在IIS6网站下运行。该网站有目录安全性接受匿名。 Web应用程序/虚拟目录启用匿名禁用Windows集成安全性。 web.config中有
How do I enable such authorization? The web app is running under a site on IIS6. The site has directory security to accept anonymous. The web app/virtual directory has anonymous disabled and Windows Integrated security enabled. The web.config has
推荐答案
您可以亚型 AuthorizeAttribute
来看看用户的和的角色。把我的头顶部(未经测试):
You can subtype AuthorizeAttribute
to look at Users and Roles. off the top of my head (untested):
using System;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
public class MyAuthorizeAttribute : AuthorizeAttribute
{
// This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.
protected override bool AuthorizeCore(HttpContextBase httpContext) {
base.AuthorizeCore(httpContext);
if ((!string.IsNullOrEmpty(Users) && (_usersSplit.Length == 0)) ||
(!string.IsNullOrEmpty(Roles) && (_rolesSplit.Length == 0)))
{
// wish base._usersSplit were protected instead of private...
InitializeSplits();
}
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated) {
return false;
}
var userRequired = _usersSplit.Length > 0;
var userValid = userRequired
&& _usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase);
var roleRequired = _rolesSplit.Length > 0;
var roleValid = (roleRequired)
&& _rolesSplit.Any(user.IsInRole);
var userOrRoleRequired = userRequired || roleRequired;
return (!userOrRoleRequired) || userValid || roleValid;
}
private string[] _rolesSplit = new string[0];
private string[] _usersSplit = new string[0];
private void InitializeSplits()
{
lock(this)
{
if ((_rolesSplit.Length == 0) || (_usersSplit.Length == 0))
{
_rolesSplit = Roles.Split(',');
_usersSplit = Users.Split(',');
}
}
}
}
这篇关于asp.net mvc的[授权()]属性混合组和用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!