作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
摘要:
我一直在尝试将用户作为使用 Identity 3.0 和本地用户帐户的 ASP.NET Core 3.0 项目的一部分进行播种,但在通过 EF 迁移进行播种时遇到了无法登录的问题;如果我在应用程序启动时执行它,它会起作用。
工作方法(在应用程序启动时):
如果我创建一个静态初始化器类并在 Configure
中调用它我的方法Startup.cs
然后一切正常,之后我可以毫无问题地登录。
ApplicationDataInitialiser.cs
public static class ApplicationDataInitialiser
{
public static void SeedData(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
{
SeedRoles(roleManager);
SeedUsers(userManager);
}
public static void SeedUsers(UserManager<ApplicationUser> userManager)
{
if (userManager.FindByNameAsync("admin").Result == null)
{
var user = new ApplicationUser
{
UserName = "admin",
Email = "admin@contoso.com",
NormalizedUserName = "ADMIN",
NormalizedEmail = "ADMIN@CONTOSO.COM"
};
var password = "PasswordWouldGoHere";
var result = userManager.CreateAsync(user, password).Result;
if (result.Succeeded)
{
userManager.AddToRoleAsync(user, "Administrator").Wait();
}
}
}
public static void SeedRoles(RoleManager<ApplicationRole> roleManager)
{
if (!roleManager.RoleExistsAsync("Administrator").Result)
{
var role = new ApplicationRole
{
Name = "Administrator"
};
roleManager.CreateAsync(role).Wait();
}
}
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
ApplicationDataInitialiser.SeedData(userManager, roleManager);
}
}
OnModelCreating
中植入用户和角色。上下文的方法,并在需要时生成 EF 迁移脚本,而不是将迁移提交到源代码管理。
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<ApplicationUser>(b =>
{
b.HasMany(e => e.UserRoles)
.WithOne(e => e.User)
.HasForeignKey(ur => ur.UserId);
});
builder.Entity<ApplicationRole>(b =>
{
b.HasMany(e => e.UserRoles)
.WithOne(e => e.Role)
.HasForeignKey(ur => ur.RoleId)
.OnDelete(DeleteBehavior.Restrict);
});
var adminRole = new ApplicationRole { Name = "Administrator", NormalizedName = "ADMINISTRATOR" };
var appUser = new ApplicationUser
{
UserName = "admin",
Email = "admin@contoso.com",
NormalizedUserName = "ADMIN",
NormalizedEmail = "ADMIN@CONTOSO.COM",
SecurityStamp = Guid.NewGuid().ToString()
};
var hasher = new PasswordHasher<ApplicationUser>();
appUser.PasswordHash = hasher.HashPassword(appUser, "PasswordWouldBeHere");
builder.Entity<ApplicationRole>().HasData(
adminRole
);
builder.Entity<ApplicationUser>().HasData(
appUser
);
builder.Entity<ApplicationUserRole>().HasData(
new ApplicationUserRole { RoleId = adminRole.Id, UserId = appUser.Id }
);
}
Login.cshtml.cs
并修改了
OnPostAsync
使用 UserName 属性检查凭据的方法,它是
PasswordSignInAsync
每次都失败的方法。这不是由于帐户被锁定或任何其他可能性,因为它们返回为
false
在
result
目的。这是一个带有新应用程序的新数据库,因此它应该在我的上下文文件中使用相同的密码哈希器兼容版本。
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}
// If we got this far, something failed, redisplay form
return Page();
}
OnModelCreating
被播种时密码不被接受。方法 - 可能是
PasswordHasher
的问题,但我没有看到任何我所做的似乎是错误的例子。
最佳答案
我认为这里的问题是您的前端希望用户名是电子邮件地址,而不是您拥有的简单“管理员”。尝试将您的应用用户更改为:
var appUser = new ApplicationUser
{
UserName = "admin@contoso.com",
Email = "admin@contoso.com",
NormalizedUserName = "ADMIN@CONTOSO.COM",
NormalizedEmail = "ADMIN@CONTOSO.COM",
SecurityStamp = Guid.NewGuid().ToString()
};
关于c# - 如何将 ASP.NET Core Identity 用户作为 EF 迁移的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58939935/
我是一名优秀的程序员,十分优秀!