哪种方法更适合验证用户凭据? [英] Which method is better to validate user credentials?

查看:51
本文介绍了哪种方法更适合验证用户凭据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该通过在 SQL 表中搜索用户名和密码来验证用户名和密码,还是应该找到用户名然后将密码与 PHP if 语句匹配?

Should I validate a username and pass word by searching for both in the SQL table Or Should I find the username then match the pass word with a PHP if statement?

  1. SELECT * FROM table WHERE username = $username AND password =$password

SELECT * FROM table WHERE username = $username...

if ($row[password] == $password){做东西}

哪种方法更安全有效?

推荐答案

问题是……你应该存储salted, 在数据库中散列密码.由于这些是每个用户/密码单独加盐,您不能直接使用 password = ? 查找它们,因为您不知道盐因此无法提前计算匹配的哈希值.如果您正确执行此操作,则必须首先按用户名获取用户记录,然后使用检索到的 salt/hash 验证密码哈希.伪代码:

The thing is… You are supposed to store salted, hashed passwords in the database. Since these are individually salted per user/password, you cannot look them up directly with password = ?, because you don't know the salt and therefore cannot calculate the matching hash in advance. If you're doing this properly, you must fetch the user record by username first, then validate the password hash using the retrieved salt/hash. Pseudocode:

$user = fetch_from_database($_POST['username']);

if (!$user) {
    throw new Exception("User doesn't exist");
}

if (!password_verify($_POST['password'], $user['password_hash'])) {
    throw new Exception('Invalid password');
}

echo 'Welcome ', $user['name'];

参见 http://php.net/password_hashhttp://php.net/password_verify.

这篇关于哪种方法更适合验证用户凭据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆