Wednesday, 29 October 2014

Connect Remote Active Directory using C# code

Sometimes it is required to get users information from remote server’s Active Directory. You may need to fetch some Groups of Active Directory. Here are sample codes which can help you.

Get all the users from AD specific group and fetch their information using Group Principal

   private static void GroupSearch()
        {
            Console.WriteLine("Start Group Search");
            try
            {
                PrincipalContext principalctx = new PrincipalContext(ContextType.Domain, YourServer/YourDomain, YourUserName, YourPassword);
                GroupPrincipal groupprinciple = GroupPrincipal.FindByIdentity(principalctx, IdentityType.Name, GroupName);
                if (groupprinciple != null)
                {
                    foreach (Principal innerprincipal in groupprinciple.GetMembers(false))
                    {
                        try
                        {
                            Console.WriteLine(((System.DirectoryServices.AccountManagement.UserPrincipal)(innerprincipal)).GivenName);
                            Console.WriteLine(((System.DirectoryServices.AccountManagement.UserPrincipal)(innerprincipal)).Surname);
                            Console.WriteLine(innerprincipal.SamAccountName);
                            Console.WriteLine(((System.DirectoryServices.AccountManagement.UserPrincipal)(innerprincipal)).EmailAddress);
                            Console.WriteLine(((System.DirectoryServices.AccountManagement.AuthenticablePrincipal)(innerprincipal)).Enabled ?? false);

                        }
                        catch (Exception exe)
                        {
                        }
                    }
                    groupprinciple.Dispose();
                    principalctx.Dispose();
                }
            }
            catch (Exception ex)
            {
            
            }
            Console.WriteLine("End of Group Search");
        }

Achieve same using Directory Searcher object with LDAP command

  private static void LDAP()
        {
            try
            {
                string DomainPath = "LDAP://YourIP/dc=yourDomain,dc=yourDomainExtension";
               
                DirectoryEntry searchRoot = new DirectoryEntry(DomainPath, "yourUserName", "yourPassword",AuthenticationTypes.Secure);
               
                DirectorySearcher search = new DirectorySearcher(searchRoot);
                search.Filter = ((memberOf=CN=YourGroupName,OU=YourDirectoryHierarchy, dc=yourDomain,dc=yourDomainExtension))";
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("userAccountControl");
                search.PropertiesToLoad.Add("displayname");//first name
                SearchResult result;
                SearchResultCollection resultCol = search.FindAll();
                if (resultCol != null)
                {
                    for (int counter = 0; counter < resultCol.Count; counter++)
                    {
                        string UserNameEmailString = string.Empty;
                        result = resultCol[counter];
                        if (result.Properties.Contains("displayname"))
                        {
                            Console.WriteLine((String)result.Properties["displayname"][0]);
                        }
                        if (result.Properties.Contains("samaccountname"))
                        {
                            Console.WriteLine((String)result.Properties["samaccountname"][0]);
                        }
                        if (result.Properties.Contains("mail"))
                        {
                            Console.WriteLine((String)result.Properties["mail"][0]);
                        }
                        if (result.Properties.Contains("userAccountControl"))
                        {
                            //Property check status of user
                        }
                       
                    }
                }
            }
            catch (Exception ex)
            {
          
            }

            Console.WriteLine("END Start LDAP");
        }

If you want to search all the users from root AD change bellow code from above lines:
search.Filter = "(&(objectClass=user)(objectCategory=person))";

If you want to get one user information change bellow code from above lines:
search.Filter = "(&(objectClass=user)(objectCategory=person) (sAMAccountName=yourUserName))";


Hope this sample codes help you!

Thursday, 25 September 2014

Authenticate WebAPI

You can authenticate your web API in simple two steps.

Step 1 – Create HTTPModule to authenticate request and register

Create file with below code and register this module to web.config

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.SessionState;

namespace ProjectNamespace
{
    public class BasicAuthHttpModule : IHttpModule
    {
        private const string Realm = "Message to display";

        public void Init(HttpApplication context)
        {
            // Register event handlers
            context.AuthenticateRequest += OnApplicationAuthenticateRequest;
            context.EndRequest += OnApplicationEndRequest;
            _trackTraceUserService = new TrackAndTraceUserService();
        }

        private static void SetPrincipal(IPrincipal principal)
        {
            Thread.CurrentPrincipal = principal;
            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = principal;
            }
        }

        // TODO: Here is where you would validate the username and password.
        private static bool CheckPassword(string username, string password)
        {
//Write your code to authenticate user
        }

        private static bool AuthenticateUser(string credentials)
        {
            bool validated = false;

            try
            {
                var encoding = Encoding.GetEncoding("iso-8859-1");
                credentials = encoding.GetString(Convert.FromBase64String(credentials));
                int separator = credentials.IndexOf(':');
                string name = credentials.Substring(0, separator);
                string password = credentials.Substring(separator + 1);

                validated = CheckPassword(name, password);
                if (validated)
                {
                    var identity = new GenericIdentity(name);
                    SetPrincipal(new GenericPrincipal(identity, null));
                }
            }
            catch (FormatException)
            {
                // Credentials were not formatted correctly.
                validated = false;

            }
            return validated;
        }

        private static void OnApplicationAuthenticateRequest(object sender, EventArgs e)
        {
            var request = HttpContext.Current.Request;
            var authHeader = request.Headers["Authorization"];
            if (authHeader != null)
            {

                var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);

                // RFC 2617 sec 1.2, "scheme" name is case-insensitive
                if (authHeaderVal.Scheme.Equals("basic",
                        StringComparison.OrdinalIgnoreCase) &&
                    authHeaderVal.Parameter != null)
                {
                    AuthenticateUser(authHeaderVal.Parameter);
                }
            }
        }

        // If the request was unauthorized, add the WWW-Authenticate header
        // to the response.
        private static void OnApplicationEndRequest(object sender, EventArgs e)
        {
            var response = HttpContext.Current.Response;
            if (response.StatusCode == 401)
            {
                response.Headers.Add("WWW-Authenticate",
                    string.Format("Basic realm=\"{0}\"", Realm));
            }
        }

        public void Dispose()
        {
        }
    }
}

Add bellow line in web.config
<system.webServer>
  <modules>
      <add name="BasicAuthHttpModule" type="ProjectNamespace.BasicAuthHttpModule, ProjectName" />
    </modules>
</system.webServer>

Step 2 – Create Web API

public class MyController : ApiController
    {
    
        [Authorize]
        public List<MyObject> Get([FromUri] MyClass data)
        {

}

Hope this helps you!!


Wednesday, 18 June 2014

Regular Expression Collection

invalid charecters ^[^<>`'~}%:;^#{*=|?]+$
email \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
website ^(((ht|f)tp(s?))\://)?(www.|[a-za-z].)[a-za-z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\:[0-9]+)*(/($|[a-za-z0-
max 8 numberic (^[0-9]{1,8})+(\[0-9])?
only .gif, .jpg, .png and .jpeg files valid for picture (.*\.([gg][ii][ff])|.*\.([jj][pp][gg])|.*\.([jj][pp][ee][gg])|.*\.([bb][mm][pp])|.*\.([pp][nn][gg])|.*\.([tt][ii][ii][ff])$)
fax [\ \/\(\)\.\+0-9\-]{7,20}
date format (dd-mm-yyyy) (0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](18|19|20)\d\d
minimum 5 character .{5}.*
date format ^(\d{1,2})-(\d{1,2})-(\d{4})$
only numeric with minimum 10 and maximum 15 ^[0-9]{10,15}
6 digits ^[0-9]{6}
two decimal digits ^[0-9]{1,2})+(\.[0-9]{1,2}
only numeric ^[0-9]+(\[0-9])?
time format ^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$|^(__:__)$
For more details:http://msdn.microsoft.com/en-us/library/ff650303.aspx