Dot-Net

使用 Active Directory 組的 ASP .NET MVC 表單授權

  • December 3, 2010

我正在嘗試使用 ASP.NET MVC 中的使用者和組對 Active Directory 進行身份驗證。

我在我的所有類上都添加了以下屬性(帳戶類除外):

[Authorize (Roles="SubcontractDB Users")]

該組位於活動目錄中的 OU=Area->OU=Groups->OU=Company->CN=SubcontractDB 下。我假設我還需要在 web.config 中設置一個 RoleManager,我嘗試如下操作:

<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 中某個組成員的使用者。

所以我最終實現了我自己的授權屬性並使用它:

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 中有一個錯誤會在 .NET 中引發(0x80005000)錯誤userPrincpal.IsMemberOf(...)。有關詳細資訊,請參見此處

如果您想知道如何根據授權失敗重定向到另一個頁面,請在此處查看我的答案:Add an error message to the view model based on controller attribute in ASP.NET MVC

引用自:https://stackoverflow.com/questions/4342271