5,421,850 members and growing! (20,942 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

CustomIdentity

By karthika_rani

Customize Identity ,Custom Principal with ADS
SQL, C# 2.0, C#, Windows, .NET, .NET 2.0VS2005, Visual Studio, Architect, DBA, Dev, Design

Posted: 17 May 2007
Updated: 17 May 2007
Views: 6,671
Bookmarked: 10 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
3 votes for this Article.
Popularity: 1.48 Rating: 3.11 out of 5
0 votes, 0.0%
1
1 vote, 33.3%
2
0 votes, 0.0%
3
2 votes, 66.7%
4
0 votes, 0.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

In this application windows identity and windows principal object are customized to fit the web environment. The IsInRole Method of Identity and Principal are customized to check the User role list in the from the Database .The Page/Component wise security is also provided in a simple way.

Incase of people in LAN (same Domain) want access to some intranet sites then for authendication you need not have to maintain any Login Table to store the login details such as ID,Password,EmailId ,and etc.You can use your workstation login id and password as the login credentitials. The login credentitials will query the LDAP and returns your IdentityCode ["Cn"] property which can be send to Your RMS Database and get the logged in users informations to the page.

How does this application works?

There are two classes CustomPrincipal ,CustomIdentity which customizes the IPrincipal and IIdentity Class respectively.

CustomIdentity :

  • Place the properties for logged user (what ever you think is needed regarding the logged in user )

  • IsInRole Method will return whether the logged user role exists in the role list container or not?

  • IsRoleURL Method will tells does logged user role has access to requested pages/Business Component ?

  • GetIdentity Method

This returns CustomIdentity object filled with the logged uer data.

    • This Method takes the domain UserId and Password as parameters and verifies with the ADS

    • If logged user present in the domain then his identity code will be returned from the ADS.

    • Pass this identity code to Database and get the user information and bind to the properties of the CustomIdentity Object

    • Return CustomIdentity object.

  • UnauthenticatedIdentity method

It returns a new empty CustomIdentity object which can be called when the user signs out.

    Above mentioned are internal methods which will be called through the CustomPrincipal Class .

CustomPrincipal :

  • IsInRole and IsRoleURL Methods call CustomIdentity's IsInRole and IsRoleURL Method respectively.

  • IsRoleURL Method will tells does logged user role has access to requested pages/Business Component ?

  • AuthenticateUser Calls GetIdentity of CustomIdentity and returns customprincipal.

  • This customprincipal object is set as the current context user

  • SignOut Calls UnauthenticatedIdentity Method of Identity

The below mentioned Classes are used in the Demo project

DataCache :

Used for Cacheing the data and persist till end of the application. Add to Cache and retrieve Cache methods are used to store and retrieve data from the cache

UIBase:

Set this as a pagebase class for all web.UI.Pages.In the pageload event check the existence of requsted url's access for that role.

    LoginAuthendicationWithADS :
    • On Application Start fetch the Roles And URLs from database and put it cache.

    • On session start the LoggedIn data in Session is set to "NO"

    • Enter the domain userid and password and click Go

    • In this event you call the CustomPrincipal AuthenticateUser method to get the user details.

    • If user is authendicated then LoggedIn data in Session is set to "YES"

    Using the code

    DataBase:

    Blocks of code should be set as style "Formatted" like this:

    //
    
    // 
    
    --Sample DataBase Script:
    
    --(to Run this application)
    
    GO
    
    CREATE TABLE [transact].[URL_Master](
    
    [URLID] [int] NOT NULL,
    
    [URLName] [varchar](500) NOT NULL,
    
    ) ON [PRIMARY]
    
    GO
    
    CREATE TABLE [transact].[RoleMaster](
    
    [RoleId] int NOT NULL,
    
    [RoleName] [varchar](50) NOT NULL
    
    
    
    ) ON [PRIMARY]
    
    GO
    
    CREATE TABLE [transact].[User](
    
    [identityCode] [int] NOT NULL,
    
    [Name] [varchar](50) NOT NULL,
    
    [Details] [varchar](500) NULL,
    
    [D_O_J] [datetime] NULL,
    
    
    
    ) ON [PRIMARY]
    
    GO
    
    CREATE TABLE [transact].[User_URL_Role](
    
    [URLID] [int] NOT NULL ,
    
    [RoleID] [int] NOT NULL
    
    ) ON [PRIMARY]
    
    GO
    
    CREATE TABLE [transact].[UserRole](
    
    [IdentityCode] [varchar](10) NOT NULL,
    
    [RoleID] [int] NULL
    
    ) ON [PRIMARY]
    
    GO
    //
UILayer

    Here Call the AuthenicateUser method of CustomPrincipal

    
if (CustomPrincipal.AuthenticateUser(UserID, UserPwd))

{



// Success, so we can access web site details.


if (HttpContext.Current.Session["LoggedIn"] == null)

{

HttpContext.Current.Session.Add("LoggedIn", "Yes");

}

else

HttpContext.Current.Session["LoggedIn"] = "Yes";

isLoggedIn = true;

}
CustomPrincipal Class

    Set this CustomPrincipal object as the CurrentContxt User

#region User Property

/// <summary>


/// Get or set the current <see cref="IPrincipal" />


/// object representing the user's identity.


/// </summary>


/// <remarks>


/// When running under IIS the HttpContext.Current.User value


/// is used, otherwise the current Thread.CurrentPrincipal


/// value is used.


/// </remarks>


public static IPrincipal User

{
set

{

if (HttpContext.Current != null)

HttpContext.Current.User = value;

Thread.CurrentPrincipal = value;

}

}

#endregion

    This Method Calls the GetIdentity method of CustomIdentity

    #region Methods
    
    public static bool AuthenticateUser(string UserID, string UserPwd)
    
    {
    
    // Gets the CustomIdentity after verifying with ADS and retrieveing User info from Database
    
    
    CustomIdentity objIdentity = CustomIdentity.GetIdentity(UserID, UserPwd);
    
    //if Authenticated then set the current Context user as CustomPrincipal
    
    
    if (objIdentity.IsAuthenticated)
    
    {
    
    objPrincipal = new CustomPrincipal(objIdentity);
    
    User = objPrincipal;
    
    }
    return objIdentity.IsAuthenticated;
    }
    
CustomIdentity Class

    Check the UserID , Password With ADS and get the user identity code .

    #region AuthedicateMe with ADS
    
    /// <summary>
    
    
    /// Get the logged in users IDcode from the ADS
    
    
    /// </summary>
    
    
    /// <returns>string IDcode</returns>
    
    
    private static string AuthedicateMe(string UserID,string Password)
    
    {
    
    //System.Configuration.ConfigurationManager.AppSettings["serverpath"].ToString()
    
    
    string DN = System.Configuration.ConfigurationManager.AppSettings["DomainName"].ToString();
    
    string strLDPPath = "LDAP://" + DN; 
    
    string strEntryPath = "(&(objectClass=user)(anr=" + UserID + "))";
    
    try
    
    {
    
    //provides easy access to active directory from managed code
    
    
    DirectoryEntry rootEntry = new DirectoryEntry(strLDPPath, DN + "\\" + UserID, Password);
    
    // DirectoryEntry rootEntry = new DirectoryEntry(null, "WDE" + "\\" + UserID, Password);
    
    //DirectoryEntry Class can be used to authenticate a username and password against active directory. 
    
    //You can force authentication to occur by retrieving the nativeObject property.
    
    
    
    // Bind to the native object to force authentication to happen
    
    Object objnative = rootEntry.NativeObject;
    
    // "User authenticated" Move to the next page.
    
    
    
    //Directory Searcher: perform queries against the active directory hierarchy 
    
    DirectorySearcher objDSearch = new DirectorySearcher(rootEntry);
    
    objDSearch.SearchScope = SearchScope.Subtree;
    
     
    
    objDSearch.Filter = strEntryPath;
    
    objDSearch.PropertiesToLoad.Add("cn");
    
    objDSearch.PageSize = 5;
    
    objDSearch.ServerTimeLimit = new TimeSpan(0, 10, 0);
    
    objDSearch.ClientTimeout = new TimeSpan(0, 10, 0);
    
    SearchResult queryResults = objDSearch.FindOne();
    
    if (queryResults != null)
    
    {
    
    // string PasswordString = System.Text.Encoding.Default.GetString((Byte[])queryResults.Properties["userPassword"][0]);
    
    return queryResults.Properties["cn"][0].ToString();
    
    }
    
    else
    
    {
    
    return string.Empty; 
    
    }
    
    }
    
    catch (Exception ex)
    
    {
    
    throw new Exception("Invalid password/UserID.Please Try again", ex); 
    
    }
    
    }
    
    
    
    #endregion

Pass this user identity code to database and get the UserInfo .Set this Info in appropriate properties of the identity class.

#region AuthenticateandAuthorizeMe

/// <summary>


/// Retrieves the Get UserInfo from the


/// </summary>


/// <returns></returns>


private static CustomIdentity AuthenticateandAuthorizeMe(string UserID, string Password)

{

try

{

PortalIdentity = new CustomIdentity();
//gets Identity code from LDAP


strIdcode = AuthedicateMe(UserID, Password);
try

{

// Get User Data


Common comm = new Common();

DbDataReader dreader = comm.GetLoggedUserData(strIdcode);

//Set the values to the Custom Identity's Properties


if (dreader.HasRows)

{

PortalIdentity.blnIsAuthenticated = true;

while (dreader.Read())

{

PortalIdentity.strIDcode = strIdcode;

PortalIdentity.strName = dreader["Name"].ToString();

PortalIdentity.strUserRole = dreader["RoleName"].ToString();

PortalIdentity.strUserRoleId = dreader["Roleid"].ToString();

if (dreader["D_O_J"] != null && dreader["D_O_J"] != DBNull.Value

&& (!string.IsNullOrEmpty(dreader["D_O_J"].ToString())))

PortalIdentity.dtRegisterDate = Convert.ToDateTime(dreader["D_O_J"].ToString());

if (dtRoleURL != null)

{

//Bind the URL to a list Container 


foreach (DataRow drow in dtRoleURL.Select("RoleName= '" + PortalIdentity.strUserRole +"'"))

{

PortalIdentity.lstUrl.Add(drow["URLName"].ToString());

}

}

PortalIdentity.lstRoleURL.Add(PortalIdentity.strUserRole, PortalIdentity.lstUrl);

}

The customidentity clas will expose the properties publicly but not the method. All methods are internal to the library.They are exposed to outside thru the customprincipal class

    Conclusion:

    The above application helps you in customizing your current context user object.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

karthika_rani



Occupation: Architect
Location: India India

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 1 of 1 (Total in Forum: 1) (Refresh)FirstPrevNext
Subject  Author Date 
Generalthis doesn't seem to work.memberShane Blake11:14 31 Jul '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 17 May 2007
Editor:
Copyright 2007 by karthika_rani
Everything else Copyright © CodeProject, 1999-2008
Web18 | Advertise on the Code Project