• Publisert
  • 4 min

Handling EPiServer users and roles - reference list

Handling users and roles are very common tasks in EPiServer and .NET projects in general. Here's a reference list of various useful membership related operations done in code.

Since EPiServer 5 R1, the authentication provider system (e.g the UnifiedPrincipal, PersonalizedData classes) used in earlier versions was completely replaced by the .NET 2.0 Membership and Role providers system. The code snippets in this list should be valid for EPiServer 5/6 and .NET 3.5/4.0. 

Because EPiServer's user system is based on the .NET Membership framework, you will find that there are a lot of ways to retrieve basically the same information about a user, depending on the context you're working with.

- Retrieving users
- Authenticating users (login/logout)
- Creating and deleting users
- Creating, assigning and deleting roles/groups
- Retrieving/setting user profile properties
- Access rights for users and roles

 

Retrieving users

Retrieving the current user:

EPiServerProfile currentUser = EPiServer.Personalization.EPiServerProfile.Current;
// or
string currentUser = EPiServer.Security.PrincipalInfo.CurrentPrincipal.Identity.Name;
// or
string currentUser = HttpContext.Current.User.Identity.Name;

Retrieving a specific user:

EPiServerProfile someUser = EPiServer.Personalization.EPiServerProfile.Get(username);
// or
MembershipUser someUser = System.Web.Security.Membership.GetUser(username);

Retrieving users by their email address:

string someUser = System.Web.Security.Membership.GetUserNameByEmail(email);
// or
MembershipUserCollection someUsers = System.Web.Security.Membership.FindUsersByEmail(email);

 

Authenticating users (login/logout)

Checking if the current user is authenticated (logged in):

bool currentUserIsLoggedIn = EPiServer.Security.PrincipalInfo.CurrentPrincipal.Identity.IsAuthenticated; 
// or
bool currentUserIsLoggedin = HttpContext.Current.User.Identity.IsAuthenticated;

Validating username/password input:

bool credentialsAreValid = System.Web.Security.Membership.ValidateUser(username, password);
// or
bool credentialsAreValid = System.Web.Security.FormsAuthentication.Authenticate(username, password); // NOTE: Only verifies credentials, does not log user in

Logging in a specific user:

EPiServer.Security.PrincipalInfo.CurrentPrincipal = EPiServer.Security.PrincipalInfo.CreatePrincipal(username); // Sets current user. NOTE: Does not check if username exists!
System.Web.Security.FormsAuthentication.SetAuthCookie(username, true); // Logs user in and creates persistent authentication ticket (cookie)

Logging out the current user:

System.Web.Security.FormsAuthentication.SignOut(); // Invalidates authentication ticket (cookie) from the browser
// Note that this will make the browser "forget" the user (when using "remember me" functionality on the login dialog)

 

Creating and deleting users

Creating a user:

MembershipCreateStatus status;
MembershipUser newUser = System.Web.Security.Membership.CreateUser(username, password, email, passwordQuestion, passwordAnswer, true, someUniqueValue, out status);
switch (status)

 case MembershipCreateStatus.Success: // NOTE: Make sure you also handle the other possible values of this enum
 DoSomethingUsefulHere();
 break;
}

Deleting a user:

bool userDeletedOk = System.Web.Security.Membership.DeleteUser(username, true); // Deletes user and all his Roles, Profile and WebPart personalization from the database

 

Creating, assigning and deleting roles/groups

Creating a role (EPiServer group):

System.Web.Security.Roles.CreateRole(rolename);

Checking if a role exists:

bool roleExists = System.Web.Security.Roles.RoleExists(rolename);

Retrieve all existing roles:

string[] allRoles = System.Web.Security.Roles.GetAllRoles();

Retrieve which roles a user belongs to:

string[] userRoles = System.Web.Security.Roles.GetRolesForUser(username);

Retrieve all users belonging to a specific role:

string[] usersInRole = System.Web.Security.Roles.GetUsersInRole(rolename); // Also check out FindUsersInRole(rolename, username)

Checking if the current user (CurrentPrincipal) belongs to a specific role:

bool currentUserIsInRole = System.Web.Security.Roles.IsUserInRole(rolename); 
// or
bool currentUserIsInRole = HttpContext.Current.User.IsInRole(rolename);
// or
bool currentUserIsInRole = EPiServer.Security.PrincipalInfo.CurrentPrincipal.IsInRole(rolename);

Checking if a specific user belongs to a specific role:

bool userIsInRole = System.Web.Security.Roles.IsUserInRole(username, rolename); 

Adding a user to a role:

System.Web.Security.Roles.AddUserToRole(userName, rolename); // Also check out AddUserToRoles(), AddUsersToRole() and AddUsersToRoles()

Removing a user from a role:

System.Web.Security.Roles.RemoveUserFromRole(userName, rolename); // Also check out RemoveUserFromRoles(), RemoveUsersFromRole() and RemoveUsersFromRoles()

Deleting a role:

bool roleDeletedOk = System.Web.Security.Roles.DeleteRole(rolename);

 

Retrieving/setting user profile properties

By default, EPiServer user profiles have some built-in properties, like Company, Country, DisplayName, Email, FirstName, LastName, Language and Title.
These are reflected in the web.config file:

<profile enabled="true" defaultProvider="SqlProfile" automaticSaveEnabled="true">
 <properties>
  <add name="Address" type="System.String" />
  <add name="ZipCode" type="System.String" />
  <add name="Locality" type="System.String" />
  <add name="Email" type="System.String" />
  <add name="FirstName" type="System.String" />
  <add name="LastName" type="System.String" />
  <add name="Language" type="System.String" />
  <add name="Country" type="System.String" />
  <add name="Company" type="System.String" />
  <add name="Title" type="System.String" />
  <add name="SubscriptionInfo" type="EPiServer.Personalization.SubscriptionInfo, EPiServer" />
  (...)
 </properties>
</profile>

Retrieving the value of a built-in property for the current user:

string email = EPiServer.Personalization.EPiServerProfile.Current.Email;

Setting the value of a built-in property for the current user:

EPiServer.Personalization.EPiServerProfile.Current.Email = email;
EPiServer.Personalization.EPiServerProfile.Current.Save();

To add custom properties to an EPiserver user profile, add a new line in the <profile><properties> node in web.config:

  <add name="MyCustomProperty" type="System.String" />
 </properties>
</profile>

Adding a value to a custom user profile property:

EPiServerProfile someUser = EPiServer.Personalization.EPiServerProfile.Get(userName);
someUser.SetPropertyValue("MyCustomProperty", someValue); // NOTE: For better error handling, check out TrySetPropertyValue(property, value)
someUser.Save(); // Equivalent to Membership.UpdateUser(username)

Retrieving the value of a (custom) user profile property:

string propValue = someUser.GetPropertyValue("MyCustomProperty"); // NOTE: For better error handling, check out TryGetPropertyValue(property)

 

Access rights for users and roles

Page and file permissions in .NET 2.0 onwards are governed by AccessControlLists (ACL), which define the object to protect, the trustee (a user, role, machine or domain) and their access level (read, create, edit etc).
Each page/file/directory etc has its own ACL. In EPiServer, this is used for the access rights system in edit/admin mode.

Accessing the ACL for a page:

AccessControlList list = CurrentPage.ACL; // ACL for current page
// or
PageAccessControlList list = new EPiServer.Security.PageAccessControlList(somePage.PageLink); // ACL for a specific page

Retrieving all current access rights settings on a specific page:

foreach (AccessControlEntry entry in list.Keys)
{
  string aclValue = "Trustee is " + entry.Name + ", AccessLevel is " + entry.Access;
}

Retrieving the access level of the current user on a page:

AccessLevel userAccess = list.GetAccessLevel(EPiServer.Security.PrincipalInfo.CurrentPrincipal);
// or
AccessLevel userAccess = list.QueryAccess(EPiServer.Security.PrincipalInfo.CurrentPrincipal);

Retrieving the access level of a specific user/role on a page:

AccessLevel accessLevel = list.QueryAccess(userOrRoleName);
bool userOrRoleHasAccess = accessLevel != AccessLevel.NoAccess; 

Checking specific access rights for the current user on a page:

bool userHasCreateAccess = list.QueryDistinctAccess(EPiServer.Security.AccessLevel.Create);

Setting access rights for a specific user/role on a specific page:

list.Add(new AccessControlEntry(usernameOrRolename, AccessLevel.Create));
list.Save();

Removing access rights for a specific user/role on the current page:

list.Remove(userOrRoleName);
list.Save();

Removing all access rights for a specific user/role on a specific page:

list.DeleteAclForMembership(somePage.PageLink, username, EPiServer.Security.SecurityEntityType.User);
list.DeleteAclForMembership(somePage.PageLink, rolename, EPiServer.Security.SecurityEntityType.Role);
list.Save();