2010-12-03 73 views
25

我正在尝试使用ASP.NET MVC中的用户和组对AD网站进行身份验证。ASP .NET MVC使用Active Directory组授予表格授权

我已经把我所有的类以下的属性(除账户类):

[Authorize (Roles="SubcontractDB Users")] 

该组下OU =区域 - > OU =组 - > OU =公司 - > CN =发现在活动目录中的SubcontractDB。我假设我还需要安装一个RoleManager中,我已经尝试做的web.config中如下:

<roleManager defaultProvider="ADRoleProvider"> 
    <providers> 
    <clear /> 
     <add name="ADMembershipProvider" 
      type="System.Web.Security.ActiveDirectoryMembershipProvider" 
      connectionStringName="ADConnectionString" 
      attributeMapUsername="sAMAccountName" /> 
    </providers> 
</roleManager> 

我的连接字符串是:

<add name="ADConnectionString" 
     connectionString="LDAP://blah.com:389/DC=blah,DC=wateva,DC=com"/> 

很显然,我这样做错误,因为这不起作用。我想要做的就是允许访问属于AD中某个组的成员的用户。

+0

是有什么办法可以防止在使用授权时被要求提供凭据?我在Intranet站点上使用Windows身份验证,需要通过AD组进行安全保护,而不是提示用户输入凭据。 – Fireworks 2014-01-16 15:54:16

回答

29

所以我最终实现我自己授权的属性和使用:

namespace Application.Filters 
{ 
    public class AuthorizeADAttribute : AuthorizeAttribute 
    { 
     public string Groups { get; set; } 

     protected override bool AuthorizeCore(HttpContextBase httpContext) 
     { 
     if (base.AuthorizeCore(httpContext)) 
     { 
      /* Return true immediately if the authorization is not 
      locked down to any particular AD group */ 
      if (String.IsNullOrEmpty(Groups)) 
       return true; 

      // Get the AD groups 
      var groups = Groups.Split(',').ToList<string>(); 

      // Verify that the user is in the given AD group (if any) 
      var context = new PrincipalContext(ContextType.Domain, "server"); 
      var userPrincipal = UserPrincipal.FindByIdentity(context, 
               IdentityType.SamAccountName, 
               httpContext.User.Identity.Name); 

      foreach (var group in groups) 
       if (userPrincipal.IsMemberOf(context, IdentityType.Name, group)) 
        return true; 
     } 
     return false; 
     } 
    } 
} 

,然后我可以简单地使用下面的上述控制器或功能

Using Application.Filters; 
... 
[AuthorizeAD(Groups = "groupname")] 

注:你可以简单地使用new PrincipalContext(ContextType.Domain);但是,.NET 4.0中存在一个错误,在userPrincpal.IsMemberOf(...)处出现(0x80005000)错误。有关详细信息,请参阅here

如果你想知道如何重定向到基于授权失败的另一页,检查我的答案在这里:Adding an error message to the view model based on controller attribute in ASP.NET MVC

+0

我喜欢你在这里所做的,除了你依靠一个简单的cookie来缓存某人被授权的事实。什么是阻止我手动添加authUserGroups cookie并绕过初始AD检查? – Tr1stan 2011-05-20 09:42:12

+0

好点,删除cookie部分。 – link664 2011-09-16 01:34:27

31

它不再需要实现自己的属性,在ASP.NET MVC 3此功能。 AspNetWindowsTokenRoleProvider适用于Active Directory用户和组。与AuthorizeAttribute使用这个你需要将以下添加到您的web.config:

<authentication mode="Windows" /> 

<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider"> 
    <providers> 
     <clear /> 
     <add 
      name="AspNetWindowsTokenRoleProvider" 
      type="System.Web.Security.WindowsTokenRoleProvider" 
      applicationName="/" /> 
    </providers> 
</roleManager> 

然后,在你的控制器或动作方法,你可以参考Active Directory组,像这样:

[Authorize(Roles = "YOURDOMAIN\\Group1, YOURDOMAIN\\Group2")]