Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Authenticating a Web service with Active Directory group

5.00/5 (3 votes)
7 Feb 2013CPOL 29.2K  
I struggled for four weeks trying to authenticate my Web service with AD group, I wanted to allow specific users to perfom specific tasks with the project. So finally I got it working and I thought I'll share this.

Introduction

This code allows a specif user from active directory to perform a specific task i.e viewing important employee information (companies can't allow every employee to have access to that kind of information)

Using the code

using System.ServiceModel;
using System.DirectoryServices.AccountManagement;

Firstly I have my web.config which looks like this (I won't post the whole file):

C#
<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>

I have two functions, and each function can be processed by a certain group of people from the AD groups. This is what I did on my functions on the service implementation:

[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 }
}

I hope someone will find this helpful and not struggle as i did.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)