Invalid Password when trying to log in

3 months ago

Se7en
Member | 13
+
0
-

Hello all…

I've been trying to figure out why I always get an “Invalid Password” error after following some basic examples.

I have a “users” database table with the following columns:

“username varchar(200) utf8mb4_general_ci”
“password varchar(40) utf8mb4_general_ci”

I created a simple account with the following code:

$this->database->table('users')->insert([
                'username' => 'newadmin',
                'password' => \Nette\Security\Passwords::hash('test'),
]);

Back in the database I now have an expected username of ‘newadmin’ and a password of ‘$2y$10$gs4.oUVd4IgsFIdsoYplAOeAbomzS8ba9’

My authenticator is as follows:

declare(strict_types=1);

namespace App\Auth;

use Nette;

class TestAuth implements Nette\Security\IAuthenticator
{
    private $database;

    public function __construct(Nette\Database\Context $database)
    {
        $this->database = $database;
    }

    public function authenticate(array $credentials)
    {
        list($username, $password) = $credentials;
        $row = $this->database->table('users')
            ->where('username', $username)->fetch();

        if (!$row) {
            throw new Nette\Security\AuthenticationException('User not found.');
        }

        if (!Nette\Security\Passwords::verify($password, $row->password)) {
            throw new Nette\Security\AuthenticationException('Invalid password.');
        }

        return new Nette\Security\Identity($row->id, $row->role, ['username' => $row->username]);
    }
}

Now when I attempt to sign/log in with the following code I get the “invalid password” issue. It detects usernames correctly, but never accepts the correct password.

$user = $this->getUser();
// correct info sent via the form
$user->login($values->name, $values->password);

Any advice as to what I'm doing wrong?

3 months ago

Šaman
Member | 2301
+
+2
-

Probably your hash not fit into database. You have 40 chars long column, but hash() returns 60 chars.

Last edited by Šaman (2019-03-22 04:26)

3 months ago

Se7en
Member | 13
+
0
-

Wow, as simple as that. I raised it to 100 and it worked fine. Is 100 overkill?

Thanks your speedy solution!

3 months ago

nightfish
Member | 139
+
0
-

Se7en wrote:

Wow, as simple as that. I raised it to 100 and it worked fine. Is 100 overkill?

From password_hash() docs: Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).