dna*_*oli 26 .net asp.net-mvc active-directory
我正在尝试使用ASP.NET MVC中的用户和组对Active Directory进行身份验证.
我在所有类中都添加了以下属性(帐户类除外):
[Authorize (Roles="SubcontractDB Users")]
Run Code Online (Sandbox Code Playgroud)
该组位于活动目录中的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>
Run Code Online (Sandbox Code Playgroud)
我的连接字符串是:
<add name="ADConnectionString"
connectionString="LDAP://blah.com:389/DC=blah,DC=wateva,DC=com"/>
Run Code Online (Sandbox Code Playgroud)
显然我做错了,因为这不起作用.我想要做的就是允许访问属于AD中某个组成员的用户.
dna*_*oli 33
所以我最终实现了自己的authorize属性并使用它:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以简单地使用以下控制器或功能
Using Application.Filters;
...
[AuthorizeAD(Groups = "groupname")]
Run Code Online (Sandbox Code Playgroud)
注意:您可以简单地使用new PrincipalContext(ContextType.Domain);但是.NET 4.0中存在一个错误,它会引发(0x80005000)错误userPrincpal.IsMemberOf(...).详情请见此处.
如果您想知道如何根据授权失败重定向到另一个页面,请在此处检查我的答案:基于ASP.NET MVC中的控制器属性向视图模型添加错误消息
小智 32
在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>
Run Code Online (Sandbox Code Playgroud)
然后,在您的控制器或操作方法上,您可以像这样引用Active Directory组:
[Authorize(Roles = "YOURDOMAIN\\Group1, YOURDOMAIN\\Group2")]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33015 次 |
| 最近记录: |