我有 2 个问题,它们似乎彼此相关,并且堆栈溢出中的其他重复项都没有回答我的问题。
首先,当PasswordSignInAsync
方法执行时,它永远不会停止或抛出任何异常,它只是继续执行:
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
其次,我想通过调用接收用户名和密码并返回用户信息的 Web 服务来验证用户,所以我覆盖checkPasswordAsync
方法,但它永远不会被执行:
public class ApplicationUserManager : UserManager<ApplicationUser>
{
//...
public override async Task<bool> CheckPasswordAsync(ApplicationUser user, string password)
{
return await Task.Run(() =>
{
return (checkUsernameAndPassword(user.username,password));
});
}
//...
}
我遇到了这个问题。
这是因为CheckPasswordAsync
方法永远不会为不在商店中的用户调用(身份数据库(。
与表中的用户一起尝试,您应该能够点击该方法。
<小时 />对于想要查看完整设置的人来说,它是这样的:
第 1 步:
添加CustomUserManager
:
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
public class CustomUserManager<TUser> : UserManager<TUser> where TUser : IdentityUser
{
public CustomUserManager(IUserStore<TUser> store, IOptions<IdentityOptions> optionsAccessor,
IPasswordHasher<TUser> passwordHasher, IEnumerable<IUserValidator<TUser>> userValidators,
IEnumerable<IPasswordValidator<TUser>> passwordValidators, ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<TUser>> logger)
: base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer,
errors, services, logger)
{
}
// THIS IS ONLY CALLED FOR USERS STORED IN YOUR IDENTITY DATABASE
public override Task<bool> CheckPasswordAsync(TUser user, string password)
{
// Add custom check using user.UserName and password
return Task.FromResult(true); // Replace this with your custom check
}
}
第 2 步:
在您的Program.cs
中注册
builder.Services
.AddDefaultIdentity<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
})
.AddUserManager<CustomUserManager<ApplicationUser>>() <----- THIS GUY
.AddEntityFrameworkStores<ApplicationDbContext>();
ApplicationUser
和ApplicationDbContext
看起来像这样:
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
第 3 步:
尝试使用以下命令登录:
var result = await _signInManager.PasswordSignInAsync("SomeUserNameInYourIdentityDatabase", "SomePassword", isPersistent: true, lockoutOnFailure: false);
而且您可以确定您会击中CheckPasswordAsync
方法。
试试这个。
ApplicationUser signedUser = UserManager.FindByEmail(model.Email);
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);