UserManager.CheckPasswordAsync和SignInManager.PasswordSignInAsync

Jim*_*hoe 9 c# asp.net-core asp.net-core-identity

使用ASP网络核心身份-用户提供密码和用户名以获取jwt令牌时,他们会将凭据发布到/ api / token

我的令牌控制器方法应该使用Usermanager来通过CheckPasswordAsync来检查密码,如果通过则返回令牌,还是应该使用signinmanager并调用PasswordSignInAsync然后根据该结果返回令牌?

我看到了两者的示例,并且想知道每种方法都有什么好处,一种方法比另一种方法更好吗?

目前,我们团队中的某人已撰写以下内容:

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但我认为其中有些事情是不必要的。

Kir*_*kin 13

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

1. UserManager.CheckPasswordAsync

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

2. SignInManager.PasswordSignInAsync

这种方法的作用更多。这是一个粗略的细分:

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

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

  • 好的,在研究了更多信息后,将signinmanger与cookie身份验证绑定在一起,因此,在我的情况下,如果我不想使用cookie,那么根据github身份信息源,我应该避免使用signinmanager。在那种情况下,要在我的无cookie的api中具有锁定等功能,我将需要自己实现这些功能。 (2认同)
  • @JimmyShoe您是否要共享示例代码,或示例实现的链接?我也在使用JWT(而不是cookie),并且惊讶于找到这样的代码有多么困难。 (2认同)