如何在 Asp.Net Core 中使用额外条件登录 - Identity SignInManager
示例,我想检查并验证用于登录的 ClientId、用户名和密码。
像这样的事情
var result = await SignInManager.PasswordSignInAsync(model.ClientId, model.Email, model.Password, model.RememberMe, shouldLockout: false);
请查看下面的完整代码
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.Email, 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();
}```
最佳答案
我建议使用 adapter pattern通过编写接口(interface)和包装类来实现原始 SignInManager.PasswordSignInAsync 接口(interface)的方法。
此包装类将具有一个方法,该方法接受客户端 ID 以及其余参数,执行验证,然后在完成后调用 SignInManager.PasswordSignInAsync。
您的登录方法将使用 . netCore dependency injection通过startup.cs。
public interface ISignInManagerAdapter
{
Task<Microsoft.AspNetCore.Identity.SignInResult> PasswordWithClientIdSignInAsync(string clientId, string userName, string password, bool isPersistent, bool lockoutOnFailure);
}
public class SignInManagerAdapter
{
private readonly IClientValidatorService _clientValidatorService;
public SignInManagerAdapter(IClientValidatorService clientValidatorService)
{
//you can add dependency injection interfaces to constructor parameter like below example.
this._clientValidatorService = clientValidatorService;
}
public async Task<Microsoft.AspNetCore.Identity.SignInResult> PasswordWithClientIdSignInAsync(string clientId, string userName, string password, bool isPersistent, bool lockoutOnFailure)
{
var validationStatus = _clientValidatorService.ValidateClientId(clientId);
if (validationStatus == "Active")
{
var result = await SignInManager.PasswordSignInAsync(model.ClientId, model.Email, model.Password, model.RememberMe, shouldLockout: false);
//do something
}
else
{
//do something
}
}
}
关于c# - Asp.Net Core - Identity SignInManager - 如何使用附加条件登录以便用户登录(例如 : ClientId, 用户名和密码)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61195571/