使用 Active Directory 组验证 Web 服务





5.00/5 (3投票s)
我为此奋斗了四周,试图使用 AD 组验证我的 Web 服务,我希望允许特定用户对项目执行特定任务。所以最终我成功了,我想分享一下。
引言
这段代码允许来自 Active Directory 的特定用户执行特定任务,例如查看重要的员工信息(公司不能允许每个员工都访问此类信息)。
使用代码
using System.ServiceModel; using System.DirectoryServices.AccountManagement;
首先,我的 web.config 文件如下所示(我不会发布整个文件)。
<system.web>
<authentication mode="Windows" />
<compilation debug="true" targetFramework="4.0" />
<customErrors mode="RemoteOnly" />
<trust level="Full" />
<identity impersonate="false" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" >
<extendedProtectionPolicy policyEnforcement="Always" />
</transport>
</security>
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
我有两个函数,每个函数可以由 AD 组中的特定人员处理。这是我在服务实现中的函数上所做的事情。
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)] Public MyFunction() { //Finds the user in Active Directory string whoAmI = ServiceSecurityContext.Current.PrimaryIdentity.Name; //Sets the context to domain PrincipalContext context = new PrincipalContext(ContextType.Domain, Environment.UserDomainName); //Specifies the context to use and the group name to look for GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "APP_EMPLOYEEWS_BIO"); //Sets the user to look for UserPrincipal user = UserPrincipal.FindByIdentity(context,whoAmI) //Checks if the user is the member of the group, if not throws an exceptions else processes the function if(!user.IsMemberOf(group)) { throw new SecurityException("Access Denied: User has no permission to process the request"); } else { //Code to process here } }
我希望有人觉得这有帮助,并且不会像我一样挣扎。