Don't miss out Virtual Happy Hour this Friday (April 26).

Try our conversational search powered by Generative AI!

Kristoffer Lindén
Dec 14, 2017
  15066
(11 votes)

Create Episerver admin user by code

After installing an Alloy site I forgot the username and password to login to Episerver and creating a local user and adding it to the Administrators group did not work for me. Maybe someone can tell me how that should work and be done!?

The old fashion way to create an Episerver user is described here:

https://world.episerver.com/blogs/Henrik-Fransas/Dates/2015/10/how-to-create-a-admin-user-through-code/

But that does not work in CMS 10 or 11 so I decided to write some code to create a user in CMS 11 and ended up with this:

[InitializableModule]
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class EpiserverInitialization : IInitializableModule
{
    private static readonly string[] _roles = { "WebAdmins", "WebEditors" };        

    public void Initialize(InitializationEngine context)
    {
        using (UserStore<ApplicationUser> store = new UserStore<ApplicationUser>(new ApplicationDbContext<ApplicationUser>("EPiServerDB")))
        {
            //If there's already a user, then we don't need a seed
            if (!store.Users.Any(x => x.UserName == "sysadmin"))
            {
                var createdUser = CreateUser(store, "sysadmin", "p@ssword", "sysadmin@mysite.com");
                AddUserToRoles(store, createdUser, _roles);
                store.UpdateAsync(createdUser).GetAwaiter().GetResult();
            }                
        }
    }

    private ApplicationUser CreateUser(UserStore<ApplicationUser> store, string username, string password, string email)
    {
        //We know that this Password hasher is used as it's configured
        IPasswordHasher hasher = new PasswordHasher();
        string passwordHash = hasher.HashPassword(password);

        ApplicationUser applicationUser = new ApplicationUser
        {
            Email = email,
            EmailConfirmed = true,
            LockoutEnabled = true,
            IsApproved = true,
            UserName = username,
            PasswordHash = passwordHash,
            SecurityStamp = Guid.NewGuid().ToString()
        };

        store.CreateAsync(applicationUser).GetAwaiter().GetResult();

        //Get the user associated with our username
        ApplicationUser createdUser = store.FindByNameAsync(username).GetAwaiter().GetResult();
        return createdUser;
    }

    private void AddUserToRoles(UserStore<ApplicationUser> store, ApplicationUser user, string[] roles)
    {
        IUserRoleStore<ApplicationUser, string> userRoleStore = store;
        using (var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext<ApplicationUser>("EPiServerDB")))
        {
            IList<string> userRoles = userRoleStore.GetRolesAsync(user).GetAwaiter().GetResult();
            foreach (string roleName in roles)
            {
                if (roleStore.FindByNameAsync(roleName).GetAwaiter().GetResult() == null)
                {
                    roleStore.CreateAsync(new IdentityRole { Name = roleName }).GetAwaiter().GetResult();
                }
                if (!userRoles.Contains(roleName))
                    userRoleStore.AddToRoleAsync(user, roleName).GetAwaiter().GetResult();
            }
        }
    }

    public void Uninitialize(InitializationEngine context)
    {
    }

    public void Preload(string[] parameters)
    {
    }
}

After this code is run I can login with the created sysadmin user.

/Kristoffer

Dec 14, 2017

Comments

Henrik Fransas
Henrik Fransas Dec 14, 2017 03:52 PM

Thanks for the updated version!

Praful Jangid
Praful Jangid Jun 18, 2019 11:49 AM

I would like to suggest here that, the simple password that do not meet the minimum level of security (like we need one caps and one small letter and numeric and special character. for example "password") will not be accepted as password and you will not be able to figure out the issue that why you are not able to login even entering the correct username and password.

I just faced the issue. Therefore, try to follow the security parameters. (example "Simple123#")

Thanks for blog, best regards

Praful Jangid

Kevin Candlert
Kevin Candlert Mar 26, 2024 09:21 PM

I made a quick and dirty upgrade to CMS 12:

[InitializableModule]
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class EpiserverInitialization : IInitializableModule
{
    private static readonly string[] _roles = { "WebAdmins", "WebEditors" };

    public void Initialize(InitializationEngine context)
    {
        var appUserManager = context.Locate.Advanced.GetService<ApplicationUserManager<ApplicationUser>>();
        var roleManager = context.Locate.Advanced.GetService<RoleManager<IdentityRole>>();
        var sysAdminExists = appUserManager.Users.ToList().Any(x => x.UserName == "sysadmin");
        if(!sysAdminExists)
        {
            var newUser = CreateUser(appUserManager, "sysadmin", "Simple123#", "noreply@mysite.com");
            AddUserToRoles(appUserManager, roleManager, newUser, _roles);
            appUserManager.UpdateAsync(newUser).GetAwaiter().GetResult();
        }
    }

    private ApplicationUser CreateUser(ApplicationUserManager<ApplicationUser> store, string username, string password, string email)
    {
        ApplicationUser applicationUser = new ApplicationUser
        {
            Email = email,
            EmailConfirmed = true,
            LockoutEnabled = true,
            IsApproved = true,
            UserName = username,
            SecurityStamp = Guid.NewGuid().ToString()
        };
        IPasswordHasher<ApplicationUser> hasher = store.PasswordHasher;
        string passwordHash = hasher.HashPassword(applicationUser, password);
        applicationUser.PasswordHash = passwordHash;

        store.CreateAsync(applicationUser).GetAwaiter().GetResult();

        //Get the user associated with our username
        ApplicationUser createdUser = store.FindByNameAsync(username).GetAwaiter().GetResult();
        return createdUser;
    }

    private void AddUserToRoles(ApplicationUserManager<ApplicationUser> store, Microsoft.AspNetCore.Identity.RoleManager<IdentityRole> roleManager, ApplicationUser user, string[] roles)
    {
        using (roleManager)
        {
            IList<string> userRoles = store.GetRolesAsync(user).GetAwaiter().GetResult();
            foreach (string roleName in roles)
            {
                if (roleManager.FindByNameAsync(roleName).GetAwaiter().GetResult() == null)
                {
                    roleManager.CreateAsync(new IdentityRole { Name = roleName }).GetAwaiter().GetResult();
                }
                if (!userRoles.Contains(roleName))
                    store.AddToRoleAsync(user, roleName).GetAwaiter().GetResult();
            }
        }
    }

    public void Uninitialize(InitializationEngine context)
    {
    }

    public void Preload(string[] parameters)
    {
    }
}

Please login to comment.
Latest blogs
Solving the mystery of high memory usage

Sometimes, my work is easy, the problem could be resolved with one look (when I’m lucky enough to look at where it needs to be looked, just like th...

Quan Mai | Apr 22, 2024 | Syndicated blog

Search & Navigation reporting improvements

From version 16.1.0 there are some updates on the statistics pages: Add pagination to search phrase list Allows choosing a custom date range to get...

Phong | Apr 22, 2024

Optimizely and the never-ending story of the missing globe!

I've worked with Optimizely CMS for 14 years, and there are two things I'm obsessed with: Link validation and the globe that keeps disappearing on...

Tomas Hensrud Gulla | Apr 18, 2024 | Syndicated blog

Visitor Groups Usage Report For Optimizely CMS 12

This add-on offers detailed information on how visitor groups are used and how effective they are within Optimizely CMS. Editors can monitor and...

Adnan Zameer | Apr 18, 2024 | Syndicated blog

Azure AI Language – Abstractive Summarisation in Optimizely CMS

In this article, I show how the abstraction summarisation feature provided by the Azure AI Language platform, can be used within Optimizely CMS to...

Anil Patel | Apr 18, 2024 | Syndicated blog

Fix your Search & Navigation (Find) indexing job, please

Once upon a time, a colleague asked me to look into a customer database with weird spikes in database log usage. (You might start to wonder why I a...

Quan Mai | Apr 17, 2024 | Syndicated blog