Search code examples
asp.net-mvcasp.net-identity

ASP Identity custom password signin not working


I'm currently trying to implement my own custom PasswordSignInAsync method on the ApplicationSignInManager, but so far it fails to authenticate even though the method won't throw any errors, here is my code in IdentityConfig.cs. I have already configured ASP Identity to use long as primary keys.

I don't know if I'm missing an additional operation for creating a correct user signin, could anyone point me what I'm missing, I haven't found any code for this. This custom function passes an additional parameter to the GenerateUserIdentityAsync method of the ApplicationUser.

public class ApplicationSignInManager : SignInManager<ApplicationUser, long>
    {
        public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
            : base(userManager, authenticationManager)
        {
        }

        public async Task<SignInStatus> PasswordSystemSignInAsync(string userName, string password, bool IsPersistent, bool shouldLockout, bool IsAdministrative, string securityCode = null)
        {
            var user = await UserManager.FindByNameAsync(userName);
            if(user != null)
            {
                bool passwordCheck = await UserManager.CheckPasswordAsync(user, password);
                if (passwordCheck)
                {
                    var signInUser = await user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager, IsAdministrative);
                    if (signInUser.IsAuthenticated)
                    {
                        return SignInStatus.Success;
                    }
                    return SignInStatus.Failure;
                }
                return SignInStatus.Failure;
            }
            return SignInStatus.Failure;
        }
}

Solution

  • In the method you create the identity but you are not sign in the generated identity. Consider this:

    public async Task<SignInStatus> PasswordSystemSignInAsync(string userName,string password, bool IsPersistent, bool shouldLockout, bool IsAdministrative, string securityCode = null)
    {
        var user = await UserManager.FindByNameAsync(userName);
        if(user != null)
        {
            bool passwordCheck = await UserManager.CheckPasswordAsync(user, password);
            if (passwordCheck)
            {
                var userIdentity = await user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager, IsAdministrative);
                AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
                AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = IsPersistent}, userIdentity);
                return SignInStatus.Success;
            }
            return SignInStatus.Failure;
        }
        return SignInStatus.Failure;
    }