如何为 MVC .Net Core 应用程序创建单个管理员用户

2024-04-05

我正在构建一个本质上是商店的网络应用程序,但我想为网站管理员提供一种简单的方法来添加新产品。但是我想限制网站的这一部分,以便只有管理员可以访问它。目前我对其他用户没有用处。

我该如何做到这一点,以便任何拥有管理员用户名和密码的人都可以访问这些页面,并且它会持续知道他们已登录?我已经有了一个系统,它接受用户输入,然后如果正确的话继续进入管理页面。但问题是,如果有人决定直接进入“管理/添加产品”等页面。我需要我的应用程序知道他们还不允许访问 AddProduct 页面并将其重定向回登录页面。


您可以通过创建一个轻松地做到这一点CreateRoles方法在你的Startup班级。这有助于检查角色是否已创建,如果没有则创建角色;在应用程序启动时。就像这样:

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] /cdn-cgi/l/email-protection");

   // 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] /cdn-cgi/l/email-protection",
        };
        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");

        }
   }
}

然后你可以打电话await CreateRoles(serviceProvider);方法从Configure方法中的Startup班级。确保您有IServiceProvider作为参数Configure class.


问题2:我如何才能使任何拥有管理员用户名和密码的人都可以访问这些页面?

答案2:您可以轻松地做到这一点,如下所示:

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

您还可以在操作方法中使用基于角色的授权,如下所示。如果您愿意,可以分配多个角色:

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

虽然这工作得很好,但为了更好的实践,您可能需要阅读有关使用基于策略的角色检查的信息。您可以在 ASP.NET core 文档中找到它here https://learn.microsoft.com/en-us/aspnet/core/security/authorization/roles,或者我写的这篇文章here https://gooroo.io/GoorooTHINK/Article/17333/Custom-user-roles-and-rolebased-authorization-in-ASPNET-core/28352#.WLQMoxIrKu4

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为 MVC .Net Core 应用程序创建单个管理员用户 的相关文章

随机推荐