gpt4 book ai didi

c# - UserManager.CheckPasswordAsync 与 SignInManager.PasswordSignInAsync

转载 作者:太空狗 更新时间:2023-10-29 20:06:48 26 4
gpt4 key购买 nike

使用 asp net core 身份 - 当用户提供密码和用户名以获取 jwt token 时,他们将凭据发布到/api/token

我的 token Controller 方法应该使用 usermanager 使用 CheckPasswordAsync 检查密码,如果通过则返回 token ,还是应该使用 signinmanager 并调用 PasswordSignInAsync 然后根据该结果返回 token ?

我看过这两种方法的例子,想知道每种方法有什么好处,一种方法比另一种方法好吗?

目前我团队中有人写了以下内容:

[AllowAnonymous]
[HttpPost]
public async Task<ActionResult<User>> Post([FromBody]User model)
{
try
{
var user = await _userManager.FindByNameAsync(model.Username);
if (user == null)
return StatusCode(StatusCodes.Status401Unauthorized, "Incorrect username or password");

var passwordOK = await _userManager.CheckPasswordAsync(user, model.Password);
if (!passwordOK)
return StatusCode(StatusCodes.Status401Unauthorized, "Incorrect username or password");

model.Id = user.Id;
model.Name = user.DisplayName;
model.Password = "";

int expiresIn;
long expiresOn;
model.Token = _authorisationService.GetJWTToken(model.Username, user.Id, out expiresIn, out expiresOn);
model.ExpiresIn = expiresIn;
model.ExpiresOn = expiresOn;

return model;
}
catch (Exception)
{
// log the exception
return StatusCode(StatusCodes.Status500InternalServerError);
}
}

但我认为其中有些东西是不必要的。

最佳答案

您提到的两种方法有不同的用途:

1。 UserManager.CheckPasswordAsync

此方法对提供的密码进行哈希处理,并将其与现有密码哈希值(例如,存储在数据库中)进行比较。

2。 SignInManager.PasswordSignInAsync

这个方法做得更多。这是一个粗略的分割:

  • 检查是否允许登录。例如,如果用户在被允许登录之前必须有一个确认的电子邮件,则该方法返回 SignInResult.Failed
  • 调用 UserManager.CheckPasswordAsync 检查密码是否正确(如上所述)。
    • 如果密码不正确且支持锁定,该方法会跟踪失败的登录尝试。如果超过配置的失败登录尝试次数,该方法会将用户锁定。
  • 如果为用户启用双因素身份验证,该方法会设置相关的 cookie 并返回 SignInResult.TwoFactorRequired
  • 最后,执行登录过程,最终创建一个 ClaimsPrincipal 并通过 cookie 保存它。

如果您对要求确认电子邮件、锁定等不感兴趣,那么在您的问题中使用 UserManager.CheckPasswordAsync 就足够了。

关于c# - UserManager.CheckPasswordAsync 与 SignInManager.PasswordSignInAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53854051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com