简体   繁体   English

Asp.NET Identity Custom SignInManager

[英]Asp.NET Identity Custom SignInManager

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. 我看到默认模板创建了一个派生自默认值的ApplicationSignInManager。

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. 首先,假设“userName”对每个用户都是唯一的。 Although, this could be safely assumed. 虽然,这可以安全地假设。

Second, the function returns practically a SignInStatus, which is defined by the Asp.net Identity. 其次,该函数实际上返回一个SignInStatus,它由Asp.net标识定义。 I cannot modify to return anything else, to convey proper reason why the login may fail. 我无法修改以返回任何其他内容,以传达登录可能失败的正当理由。

Could anyone provide good solutions to this? 谁能为此提供良好的解决方案?

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 . 并更改您的控制器以使用您的新方法而不是标准的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? 否则,如果有2个帐户具有相同的用户名,系统将如何知道尝试密码的帐户?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM