且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何防止用户直接在ASP.Net MVC 5中访问某些URL

更新时间:2022-04-15 07:40:35

假设您的令牌实际上是唯一的,那么您实际上不需要知道用户的电子邮件地址/用户名.令牌充当用户记录的(临时)唯一ID,因此您只需在输入新密码"视图中保留该令牌,然后在重置逻辑中使用该令牌即可:

Assuming your tokens are actually unique, you don't actually need to know the email address / user name for the user. The token acts as a (temporary) unique ID for a user record, so you can just persist that token within the "enter your new password" view, and use that within your reset logic:

public bool UpdatePasswordForToken(string token, string newPassword)
{
    bool success = false;

    var user = Context.Users.SingleOrDefault(u => u.ResetToken.Equals(token, StringComparison.OrdinalIgnoreCase));
    if (user != null)
    {
        var password = Crypto.HashPassword(newPassword);
        if (!string.IsNullOrWhiteSpace(password))
        {
            user.Password = password;
            user.ResetToken = null;

            Context.SaveChanges();

            success = true;
        }
    }

    return success;
}

这假定您不只是在用户完成密码重置后登录.我重定向到登录页面(带有成功消息).即使有人设法猜测出有效的重置令牌(这意味着令牌并不是唯一的),他们也需要知道他们刚刚重置了哪个用户名,才能以(现在受到威胁)的用户身份登录.

This assumes that you don't just log the user in when they complete the password reset. I redirect to the login page (with a success message). Even if someone managed to guess a valid reset token (which means the tokens aren't really unique), they would need to know which user name they just reset, in order to log in as the (now compromised) user.

如果仅在工作流程之后才真正对用户进行设置,那么显而易见的答案似乎是检查Request.UrlReferrer值,如果不是要执行此操作的操作,则将该用户从当前操作中退回.不过,UrlReferrer并不是防弹的,因此,我建议像上面提到的那样简化您的工作流程.

If you're really set on a user only following your workflow, the obvious answer seems to be checking the Request.UrlReferrer value, and bouncing the user from the current action if it's not the action you wanted to proceed this action. UrlReferrer isn't bulletproof, though, so I would recommend just simplifying your workflow like I note above.