Programmatically Accessing the Currently Logged-in User

How to retrieve information about currently logged user and his/her roles in the Code Customization?

Verifying that the currently logged-in user has particular role(s)

This is applicable for all security types, including database security and Active Directory security.

C#:

BaseClasses.Utils.SecurityControls.IsUserInRole(System.Web.HttpContext.Current, "role1;role2;role3");

Visual Basic .NET:

BaseClasses.Utils.SecurityControls.IsUserInRole(System.Web.HttpContext.Current, "role1;role2;role3")

Retrieve the logged-in user’s user ID

This applies to database security only.

C#:

string UserID = this.Page.SystemUtils.GetLoginId();

Visual basic .NET:

Dim userID As String = Me.Page.SystemUtils.GetLoginId()

Retrieve the current user’s roles

This applies to retrieving Active Directory security roles.

C#:

System.Web.SessionState.HttpSessionState mySession = System.Web.HttpContext.Current.Session;

string usrRoleStr = (string) mySession.Item(SessionConst.UserRole);

Visual Basic .NET:

Dim mySession As System.Web.SessionState.HttpSessionState = System.Web.HttpContext.Current.Session

Dim usrRoleStr As String = CType(mySession.Item(SessionConst.UserRole), String)

Retrieve the logged-in user’s username

This is applicable for all security types, including database security and Active Directory security.

The GetUserStatus function returns ‘null’ or ‘Nothing’ if the user is not logged in and returns the user name as a string if the user is logged in.

C#:

((BaseApplicationPage)(this.Page)).CurrentSecurity.GetUserStatus();

Visual Basic .NET:

DirectCast(Me.Page, BaseApplicationPage).CurrentSecurity.GetUserStatus()

For Active Directory Directory security, you can access the user name in a class other than the page-derived class:

C#:

System.Web.SessionState.HttpSessionState mySession = System.Web.HttpContext.Current.Session;

string usrName = (string) mySession.Item(SessionConst.UserName);

Visual Basic .NET:

Dim mySession As System.Web.SessionState.HttpSessionState = System.Web.HttpContext.Current.Session

Dim usrName As String = CType(mySession.Item(SessionConst.UserName), String)

See Also

Security and Authentication