Showing posts with label Active Directory. Show all posts
Showing posts with label Active Directory. Show all posts

Friday, September 25, 2009

Authenticate user via Active Directory - ASP.NET - C#

Authentication is one of most important process of asp.net application ,there are four modes which can be defined in web.config file, "Passport", "Windows", "Forms" and "None".
many applications use Forms Mode which means you should design a login.aspx page and user enter username and password , however many useres suffer to memorize many user name and password for working with applications, one of the most suitable way to release from this problem is used the same user name and password which users use to logon to his/her computer , I mean the same user name and password in Active Directory. using this class provides this facility for the application. just create an instance of the class and call IsExistedDomainUser function.

using System;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.DirectoryServices;


///
/// User can be authenticated with existing User Name and password in Active Directory
/// LdapPath such as LDAP://ServerName/DC=MyCompany,DC=COM
///
public class LDAPAuthentication
{
string _LdapPath;
string _FilterAttribute;


public LDAPAuthentication(string LdapPath)
{
_LdapPath = LdapPath;

}

public bool IsExistedDomainUser(System.Web.HttpResponse Response, string strUsername, string strDomain, string strPassword, bool isCookiePersistent)
{

if (IsAuthenticated(strDomain, strUsername, strPassword) == true)
{

//Create the ticket, and add the groups.
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, strUsername, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, FormsAuthentication.FormsCookiePath);

//Encrypt the ticket.
string strEncryptedTicket = FormsAuthentication.Encrypt(authTicket);

//Create a cookie, and then add the encrypted ticket to the cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEncryptedTicket);

if (isCookiePersistent == true)
authCookie.Expires = authTicket.Expiration;

//Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);

//If user registerd in Doamin
return true;
}
else
//If user does not registerd in Doamin
return false;

}

private bool IsAuthenticated(string domain, string username, string pwd)
{
string domainAndUsername = domain + "\\" + username;
DirectoryEntry entry = new DirectoryEntry(_LdapPath, domainAndUsername, pwd);
try
{
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if ((result == null))
{
return false;
}
_LdapPath = result.Path;
_FilterAttribute = ((string)result.Properties["cn"][0]);
}
catch
{
throw new Exception("Incorrect User name or passowrd, try again!");
}
return true;
}
}
//-----------------------------------------------------------------
changing Web.Config and set your logon form name with the following syntax
Logon page in this example is Logon.aspx in the
authentication tag
forms name="AuthCookie" loginUrl="Logon.aspx"

Thursday, September 24, 2009

Impersonate User in Active Directory - ASP.NET

Via the following class you can athenticate s specific user to specific domain and after that you access the resources (such as Doc or anything else) , and finally call UndoImpersotae function to disconnect athenticated user.

For inctance your application is installed on AppServer.WemDomain.local and you need to access some resources on FileServer.FileDomain.local , so you should have a user in FileDomain.local and then authenticate it and access to the resources and then close athentication proccess all these thing is happened in background and the user could not understand where the file come from.

public class ImpersonateUser_ActiveDirectory
{

public const int LOGON32_LOGON_INTERACTIVE = 9;
public const int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);

//Athenticate specific user in Active Directory
public bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}

//Undo authentication for authenticated user
private void undoImpersonation()
{
impersonationContext.Undo();
}
}

--------------------------------------------------------

you can save user info and domain info in Web.config and read these information with the following syntax

string UserName = ConfigurationSettings.AppSettings["UserName"];