首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在asp.net MVC5中显示锁定结束时间

问如何在asp.net MVC5中显示锁定结束时间
EN

Stack Overflow用户
提问于 2017-07-21 05:30:02
回答 1查看 447关注 0票数 0

我已经创建了一种机制,它将根据用户输入错误密码的时间来增加锁定结束时间。

代码语言:javascript
复制
case SignInStatus.LockedOut:
{
    if (failedAttempt > 0)
    {
        user.LockoutEnabled = true;
        user.LockoutEndDateUtc = DateTime.UtcNow.AddMinutes(5* failedAttempt);
        await UserManager.UpdateAsync(user);
    }
    return View("Lockout");
} 

我想在“锁定”视图中为用户显示这一点:

代码语言:javascript
复制
@model System.Web.Mvc.HandleErrorInfo   
@{
     ViewBag.Title = "locked";
}

<hgroup>
    <h1 class="text-danger">Verrouillé.</h1>
    <h2 class="text-danger">Ce compte a été verrouillé, veuillez réessayer./h2>
</hgroup>

怎么做?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-21 05:57:22

如果您遵循的方案是,当用户无效时,它只会减少无效的尝试。除非用户正确输入登录凭据,否则它不会实际挂起用户。

实际上,你的逻辑应该是:

  • 验证凭据
  • 有效凭据
  • 检查帐户状态,挂起,然后拒绝访问。
  • 将尝试重新设置为5
  • 允许用户进入应用程序
  • 凭据无效
  • 减少一次尝试
  • 如果需要,将帐户设置为暂停。

这个逻辑的很多部分实际上可以被绑定到一两种方法中。同样在DecreaseAttempts()方法中,您有两个SQL命令,其中从未执行sql命令cmd。

下面是一个在返回状态枚举的方法中执行此操作的示例。现在,这是一个非常基本的示例,但只需要一个方法来执行您的完全授权方法。我已经对代码进行了评论。

代码语言:javascript
复制
public partial class UserManager 
{

    const int MaxAttempts = 5;

    public LoginStatus ValidateUser(string username, string password)
    {
        if (string.IsNullOrWhiteSpace(username))
            throw new ArgumentNullException("username");

        //set the password to empty if it is null
        password = password ?? "";

        //create the connection
        using (var connection = new SqlConnection(Configuration.ConnectionString))
        {
            //assign some local variables
            int attemptsLeft = MaxAttempts;
            string currentStatus = "Active";
            string userPassword = null;

            //get the information for the user, only query by username so we have all the data. We will match the password later on
            string query = "SELECT TOP(1) [Username], [Password], [AttemptsLeft], [CurrentStatus] FROM [Information] WHERE Username = @username";

            using (var command = new SqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@username", username);
                command.CommandType = System.Data.CommandType.Text;

                connection.Open();

                using (var reader = command.ExecuteReader())
                {
                    //no rows.. Invalid username
                    if (!reader.HasRows)
                    {
                        connection.Close();
                        return LoginStatus.InvalidCredentials;
                    }

                    //read the first row (hence the break)
                    while (reader.Read())
                    {
                        attemptsLeft = (int)reader["AttemptsLeft"];
                        currentStatus = (string)reader["CurrentStatus"];
                        userPassword = (string)reader["Password"];
                        break;
                    }
                    reader.Close();
                }
                connection.Close();
            }

            //if the account is suspended then dont even bother with password checking
            if (currentStatus.Equals("Suspended", StringComparison.CurrentCultureIgnoreCase))
            {
                return LoginStatus.Suspended;
            }

            //invalid password lets handle the invalid credentials logic
            if (!password.Equals(userPassword))
            {
                attemptsLeft -= 1;

                //decrease the attempts, lets just stop at zero as we dont need negative attempts
                if(attemptsLeft >= 0)
                {
                    query = "UPDATE [Information] SET [AttemptsLeft] = @attemptsLeft WHERE Username = @username";
                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@username", username);
                        command.Parameters.AddWithValue("@attemptsLeft", attemptsLeft);
                        connection.Open();
                        command.ExecuteNonQuery();
                        connection.Close();
                    }
                }

                //suspend the account when attempts less than or equal to zero
                if (attemptsLeft <= 0)
                {
                    query = "UPDATE [Information] SET [CurrentStatus] = @currentStatus WHERE Username = @username";
                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@username", username);
                        command.Parameters.AddWithValue("@currentStatus", "Suspended");
                        connection.Open();
                        command.ExecuteNonQuery();
                        connection.Close();
                    }
                    //exit method as login account suspended
                    return LoginStatus.Suspended;
                }

                //exit as invalid login credentials
                return LoginStatus.InvalidCredentials;
            }
            //if we are here lets quickly reset the login attempts back to 5, and account status to active as this is a valid login
            query = "UPDATE [Information] SET [AttemptsLeft] = @attemptsLeft, [CurrentStatus] = @currentStatus WHERE Username = @username";
            using (var command = new SqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@username", username);
                command.Parameters.AddWithValue("@attemptsLeft", MaxAttempts);
                command.Parameters.AddWithValue("@currentStatus", "Active");
                connection.Open();
                command.ExecuteNonQuery();
                connection.Close();
            }
            //if we got here then every thing is a match
            return LoginStatus.Authorized;
        }
    }

}

public enum LoginStatus
{
    Authorized,
    InvalidCredentials,
    Suspended
}   

要使用它,可以像下面这样简单(注意,您必须更改视图重定向)

代码语言:javascript
复制
[HttpPost]
public ActionResult Index(string username, string password)
{
    if(string.IsNullOrWhiteSpace(username))
    {
        this.ModelState.AddModelError("", "Invalid Login Credential. No username sent.");
        return View();
    }

    var manager = new UserManager();

    var result = manager.ValidateUser(username, password);

    switch (result)
    {
        case LoginStatus.Authorized:
            return RedirectToAction("About", "Home");

        case LoginStatus.InvalidCredentials:
            this.ModelState.AddModelError("", "Invalid Login Credentials. Username or password incorrect");
            break;

        case LoginStatus.Suspended:
            this.ModelState.AddModelError("", "Account Suspeneded");
            break;
    }

    return View();
}

为了好玩,我把它重写成一个简单的存储过程。

代码语言:javascript
复制
CREATE PROCEDURE ValidateUser
    @username nvarchar(50),
    @password nvarchar(50)
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @userPassword nvarchar(50) = NULL
    DECLARE @maxAttempts int  = 5
    DECLARE @attemptsLeft int = 5
    DECLARE @currentStatus nvarchar(50)

    /*
        RETURN CODES:
        0 = Authorized
        1 = InvalidCredentials
        2 = Suspended
    */


    SELECT TOP(1) @userPassword = [UserName], @attemptsLeft = [AttemptsLeft], @currentStatus = [CurrentStatus] FROM [Information] WHERE UserName = @username

    IF @userPassword IS NULL
        BEGIN
            SELECT 1 as [Result], @maxAttempts as [AttemptsRemaining]
            RETURN
        END

    --account suspended.. Return a suspended result
    If @currentStatus = 'Suspended'
        BEGIN
            SELECT 2 as [Result], 0 as [AttemptsRemaining]
            RETURN
        END

    --passwords dont match (note this is case insensitive on default collation)
    If @password IS NULL OR @password <> @userPassword
        BEGIN
            --decrease attempts
            SET @attemptsLeft = @attemptsLeft - 1

            --if the attempts left are greater than 0 then set the account active and decrease the attempts remaining
            IF @attemptsLeft > 0
                BEGIN
                    UPDATE [Information] SET [CurrentStatus] = 'Active', AttemptsLeft = @attemptsLeft WHERE UserName = @username
                    SELECT 1 as [Result], @attemptsLeft as [AttemptsRemaining]
                    RETURN
                END
            --else the attempts left are less than or equal to zero therefore they should be suspended and attempts left set to zero (dont want negative attempts)
            ELSE
                BEGIN
                    UPDATE [Information] SET [CurrentStatus] = 'Suspended', AttemptsLeft = 0 WHERE UserName = @username
                    SELECT 2 as [Result], 0 as [AttemptsRemaining]
                    RETURN
                END
        END
    --if we get here then all is good and we can just reset the account status and max attempts for the next login attempt
    UPDATE [Information] SET [CurrentStatus] = 'Active', AttemptsLeft = @maxAttempts WHERE UserName = @username
    SELECT 0 as [Result], @maxAttempts AS [AttemptsRemaining]

END
GO

然后调用这非常简单(注意,我还将返回类型更改为返回状态和剩余尝试的调用。

方法

代码语言:javascript
复制
public LoginResult ValidateUserStoredProcedure(string username, string password)
{
    if (string.IsNullOrWhiteSpace(username))
        throw new ArgumentNullException("username");

    //set the password to empty if it is null
    password = password ?? "";

    //create the connection
    using (var connection = new SqlConnection(Configuration.ConnectionString))
    {
        var result = new LoginResult
        {
            AttemptsRemaining = 5,
            Status = LoginStatus.InvalidCredentials
        };
        try
        {
            using (var command = new SqlCommand("EXEC ValidateUser @username, @password", connection))
            {
                command.Parameters.AddWithValue("@username", username);
                command.Parameters.AddWithValue("@password", password);
                command.CommandType = System.Data.CommandType.Text;
                connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        result.Status = ((LoginStatus)(int)reader["Result"]);
                        result.AttemptsRemaining = (int)reader["AttemptsRemaining"];
                        break;
                    }
                    reader.Close();
                }
                connection.Close();
            }
            return result;
        }
        catch (Exception ex)
        {
            if (connection.State != System.Data.ConnectionState.Closed)
                connection.Close();

            Debug.WriteLine("Error on sql query:" + ex.Message);
            return result;
        }
    }
}

结果类

代码语言:javascript
复制
public class LoginResult
{
    public LoginStatus Status { get; set; }

    public int AttemptsRemaining { get; set; }
}

public enum LoginStatus : int
{
    Authorized = 0,
    InvalidCredentials = 1,
    Suspended = 2
}

控制器

代码语言:javascript
复制
[HttpPost]
public ActionResult Index(string username, string password)
{
    if (string.IsNullOrWhiteSpace(username))
    {
        this.ModelState.AddModelError("", "Invalid Login Credential. No username sent.");
        return View();
    }
    var manager = new UserManager();
    var result = manager.ValidateUserStoredProcedure(username, password);
    switch (result.Status)
    {
        case LoginStatus.Authorized:
            return RedirectToAction("About", "Home");

        case LoginStatus.InvalidCredentials:
            if (result.AttemptsRemaining < 5)
                this.ModelState.AddModelError("", "Invalid Login Credentials. Username or password incorrect. Attempts remaining:" + result.AttemptsRemaining);
            else
                this.ModelState.AddModelError("", "Invalid Login Credentials. Username or password incorrect.");
            break;

        case LoginStatus.Suspended:
            this.ModelState.AddModelError("", "Account Suspeneded");
            break;
    }
    return View();
}

如何优化取决于您自己,但这种授权级别相当薄弱。它还显示您正在将密码存储为纯文本。但这是另一个共同的话题。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45229652

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档