簡體   English   中英

使用entityframework core登錄asp.net core app

[英]Sign In in asp.net core app with entityframework core

我繼承了 IdentityUser class 只是為了添加 FirstName 和 LastName 屬性。因此,SignInManager class 提供了兩種登錄方式,要么將用戶名鍵入字符串,要么傳遞繼承 IdentityUser 的 ApplicationUser class。

public class ApplicationUser: IdentityUser
{
   public string FirstName {get; set;}
   public string LastName {get; set;}
}

現在,您可以通過兩種不同的方式登錄 其中一種方式是:

await _signInManager.SignInAsync(new ApplicationUser{UserName = someclass.userName}, someclass.password, true, false);

另一種方法是:

await _signInManager.SignInAsync(someclass.userName, someclass.password, true, false);

通過傳遞用戶信息 object 登錄用戶會拋出錯誤,提示密碼不正確,但通過傳遞字符串用戶名登錄用戶會像第二種方式一樣成功登錄。為什么? 而且,即使您已通過第二種方式登錄用戶,VerifyUserTokenAsync 也不會工作,您無法重置密碼或更改 email 地址。 幫我解決這個問題。 我想通過第一種技術登錄用戶。

使用SignInAsync(new ApplicationUser{...})時,您不會從數據庫中加載用戶 object 的 rest。 這意味着IdentityUser.PasswordHash字段為空。

public virtual async Task<SignInResult> PasswordSignInAsync(TUser user, string password, bool isPersistent, bool lockoutOnFailure)
{
    if (user == null)
    {
        throw new ArgumentNullException(nameof(user));
    }

    var attempt = await CheckPasswordSignInAsync(user, password, lockoutOnFailure);
    return attempt.Succeeded
        ? await SignInOrTwoFactorAsync(user, isPersistent)
        : attempt;
}

https://github.com/do.net/as.netcore/blob/746b9f82fb5c026ce3ce1aed9b2883078ca9ebe6/src/Identity/Core/src/SignInManager.cs#L330

使用SignInAsync(username, password) ,身份框架會為您加載用戶,然后檢查憑據,這就是您不會收到錯誤的原因。

public virtual async Task<SignInResult> PasswordSignInAsync(string userName, string password,
        bool isPersistent, bool lockoutOnFailure)
{
    var user = await UserManager.FindByNameAsync(userName); // <---
    if (user == null)
    {
        return SignInResult.Failed;
    }

    return await PasswordSignInAsync(user, password, isPersistent, lockoutOnFailure);
}

https://github.com/do.net/as.netcore/blob/746b9f82fb5c026ce3ce1aed9b2883078ca9ebe6/src/Identity/Core/src/SignInManager.cs#L357

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM