How to make a single admin user for MVC .Net Core app

asp.net-core, asp.net-mvc, authentication, c#

Solution

You could do this easily by creating a `CreateRoles` method in your `Startup` class. This helps check if the roles are created, and creates the roles if they aren't; on application startup. Like so:

private async Task CreateRoles(IServiceProvider serviceProvider)
{
    //initializing custom roles 
    var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
    string[] roleNames = { "Admin", "Store-Manager", "Member" };
    IdentityResult roleResult;

    foreach (var roleName in roleNames)
    {
        var roleExist = await RoleManager.RoleExistsAsync(roleName);
        // ensure that the role does not exist
        if (!roleExist)
        {
            //create the roles and seed them to the database: 
            roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
        }
    }

    // find the user with the admin email 
    var _user = await UserManager.FindByEmailAsync("admin@email.com");

   // check if the user exists
   if(_user == null)
   {
        //Here you could create the super admin who will maintain the web app
        var poweruser = new ApplicationUser
        {
            UserName = "Admin",
            Email = "admin@email.com",
        };
        string adminPassword = "p@$$w0rd";

        var createPowerUser = await UserManager.CreateAsync(poweruser, adminPassword);
        if (createPowerUser.Succeeded)
        {
            //here we tie the new user to the role
            await UserManager.AddToRoleAsync(poweruser, "Admin");

        }
   }
}

and then you could call the `await CreateRoles(serviceProvider);` method from the `Configure` method in the `Startup` class. Ensure you have `IServiceProvider` as a parameter in the `Configure` class.

Question 2: How do I make it so that anybody with the admin username and password can access these pages?

Answer 2: You can do this easily, like so:

[Authorize(Roles="Admin")]
public class ManageController : Controller
{
   //....
   Return View();
}

You can also use role-based authorization in the action method like so. Assign multiple roles, if you will:

[Authorize(Roles="Admin")]
public IActionResult Index()
{
/*
 .....
 */ 
}

While this works fine, for a much better practice, you might want to read about using policy based role checks. You can find it on the ASP.NET core documentation here, or this article I wrote about it here

Problem

I'm building a web app that is essentially a store, but I want to put in an easy way for the admin of the site to add new products. However I want to restrict this part of the site so only the admin can access it. I have no use for other users at this moment. How do I make it so that anybody with the admin username and password can access these pages and it will persist to know that they are logged in? I already have a system in place that accepts a user input and then continues to the admin pages if it's correct. But the problem is if someone decides to just go directly to the pages like Admin/AddProduct. I'd need my app to know that they're not allowed to access the AddProduct page yet and redirect them back to the login.

Original source

Related problems