您可以通过创建一个轻松地做到这一点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