Asp.NET Identity Custom SignInManager

26,697

Why not just create another method instead of overriding? Your method will return whatever you need to know - return object that will know if account is actually logged in or disabled by admin (I think "disabled" is a better name for this - avoids confusion). And change your controllers to use your new method instead of the standard PasswordSignIn.

Regarding username uniqueness - yes, the usernames are unique - this is the only way users can sign-in. Otherwise if there are 2 accounts with the same username, how would the system know which account to try the password against?

Share:
26,697
phandinhlan
Author by

phandinhlan

Updated on July 27, 2022

Comments

  • phandinhlan
    phandinhlan almost 2 years

    In my application, I would like to add additional conditions in order for users to login. For example, the Admin is allowed to "lock" a user account, for some reason. When account is locked, the user cannot log in. Note that this is different for the "lock out" due to multiple failed login attempts. The lock condition could be removed by the Admin.

    I see that the default template creates a ApplicationSignInManager that derives from the default.

    public class ApplicationSignInManager : SignInManager<User, string>
    

    The "Login" action from the "Account" controller calls

    var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
    

    So my attempt is to override this function

    public override async Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
    {
        User user = this.UserManager.FindByName(userName);
        if (null != user)
        {
            if (true == user.AccountLocked)
            {
                return (SignInStatus.LockedOut);
            }
        }
    
        var result = await base.PasswordSignInAsync(userName, password, isPersistent, shouldLockout);
    
        return (result);
    }
    

    There are 2 problems with this. First, this assumes that the "userName" is unique for each user. Although, this could be safely assumed.

    Second, the function returns practically a SignInStatus, which is defined by the Asp.net Identity. I cannot modify to return anything else, to convey proper reason why the login may fail.

    Could anyone provide good solutions to this?