Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 333
Joe Higley Avatar asked May 02 '17 06:05

Joe Higley


2 Answers

Here's how you go about it Joey

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("[email protected]");

       // 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 = "[email protected]",
            };
            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 "

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

like image 110
Temi Lajumoke Avatar answered Oct 21 '22 16:10

Temi Lajumoke


Once you add ASP.NET Identity to your project you can implement Role based Authorization in your application. Basically it allows you to setup [Authorize(Roles = "Administrator")] attribute for contollers which shall be available for admin users only.

like image 5
Alexey Andrushkevich Avatar answered Oct 21 '22 14:10

Alexey Andrushkevich