接下来我会处理任务。首先,我使用了 Paul Madson 在How to create roles in asp.net core and assign them to users 中提出的代码。上述方法我已插入 Startup.cs。它创建管理员角色并将其分配给种子用户。
private void CreateRoles(IServiceProvider serviceProvider)
{
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
Task<IdentityResult> roleResult;
string email = "someone@somewhere.com";
//Check that there is an Administrator role and create if not
Task<bool> hasAdminRole = roleManager.RoleExistsAsync("Administrator");
hasAdminRole.Wait();
if (!hasAdminRole.Result)
{
roleResult = roleManager.CreateAsync(new IdentityRole("Administrator"));
roleResult.Wait();
}
//Check if the admin user exists and create it if not
//Add to the Administrator role
Task<ApplicationUser> testUser = userManager.FindByEmailAsync(email);
testUser.Wait();
if (testUser.Result == null)
{
ApplicationUser administrator = new ApplicationUser
{
Email = email,
UserName = email,
Name = email
};
Task<IdentityResult> newUser = userManager.CreateAsync(administrator, "_AStrongP@ssword!123");
newUser.Wait();
if (newUser.Result.Succeeded)
{
Task<IdentityResult> newUserRole = userManager.AddToRoleAsync(administrator, "Administrator");
newUserRole.Wait();
}
}
}
然后,在 Configure 方法的同一个文件中,我添加了参数 (IServiceProvider serviceProvider),因此您应该有类似 Configure(..., IServiceProvider serviceProvider) 的内容。在配置方法的末尾我添加了
CreateRoles(serviceProvider).
要使此代码正常工作,请在某个位置创建 ApplicationUser 类,例如在 Data 文件夹中:
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Sobopedia.Data
{
public class ApplicationUser: IdentityUser
{
public string Name { get; set; }
}
}
最后,在 ConfigureServices 内部方法替换
services.AddIdentity<ApplicationUser>()
.AddEntityFrameworkStores<SobopediaContext>()
.AddDefaultTokenProviders();
与
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<SobopediaContext>()
.AddDefaultTokenProviders();
因此,程序在 AspNetRoles 表中启动后,您将获得一个新角色,而在 AspNetUsers 表中,您将获得一个新用户,即管理员角色。
不幸的是,添加以下代码后
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<SobopediaContext>()
.AddDefaultTokenProviders();
页面登录和注册停止工作。为了解决这个问题,您可以按照以下步骤操作:
脚手架身份跟随 (https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.1&tabs=visual-studio)。
然后在整个解决方案中用 IdentityUser 替换 ApplicationUser。在 ApplicationUser 类中只保留 IdentityUser 继承。
如果您没有实现,请从 Areas/identity/Pages/Account/Register.cs 中删除所有与 EmailSernder 相关的内容。
为了检查角色系统的正确性,您可以执行以下操作。在 Startup.cs 的 ConfigureServices 方法末尾添加以下代码:
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
});
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizeFolder("/Contact","RequireAdministratorRole");
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
如果它不起作用,那么只需将 [Authorize(Roles = "Administrator")] 添加到 Contact Page 模型,因此它看起来像这样:
namespace Sobopedia.Pages
{
[Authorize(Roles = "Administrator")]
public class ContactModel : PageModel
{
public string Message { get; set; }
public void OnGet()
{
Message = "Your contact page.";
}
}
}
现在,为了打开联系页面,您应该使用登录名 someone@somewhere.com 和密码 _ASstrongP@ssword!123 登录。