Security beyond the checklist in a Laravel app · Part 4 of 6

Security9 min read

Authentication and cryptographic failures: tokens, passwords and a second factor

The secrets that decide who a request is from: an API token hashed not stored, a password change that proves you are the owner now, and a two-factor seed encrypted at rest with a constant-time check and a rate limit. Hash versus encrypt, and why each is which.

By Abhishek Fouzdar

The first three parts were about requests: who may send them and what they carry. This one is about the secrets that decide who a request is from, and how they are kept. The 2025 OWASP Top 10 splits this across two categories, Authentication Failures and Cryptographic Failures, and they are hard to separate in practice because a password, a token and a two-factor seed are all secrets whose storage is the authentication. NoteMini from part 3 grows three account features here: API tokens for the mobile client, a password change, and two-factor authentication. Each one is a place to store a secret the wrong way, and each gets a test that reads the secret back the way an attacker with the database would.

1. The token kept the way it was shown

The mobile client should not carry the user's password, so it gets a token: a random string it sends as a bearer header. Creating one is a few lines, and the obvious thing to do with the random string is to save it:

public function store(Request $request): RedirectResponse
{
    $data = $request->validate(['name' => ['required', 'string', 'max:60']]);

    $token = Str::random(48);

    $request->user()->apiTokens()->create(['name' => $data['name'], 'token_hash' => $token]);

    return back()->with('status', 'Token created.')->with('plain_token', $token);
}

The column is called token_hash, which is the giveaway that someone meant to hash it and did not; what it holds is the token itself. Authentication reads it back the same way:

$token = ApiToken::where('token_hash', $bearer)->first();

This works perfectly, which is the problem. A stored secret that equals the secret the user holds is a secret the database holds too, and a database is read by backups, by replicas, by a support tool, by a log that caught a slow query, and, on the bad day the whole category is about, by whoever gets a copy of it. A password is never stored this way, because Laravel hashes it behind the hashed cast and everyone knows passwords are hashed. A token is the same kind of secret and gets none of that reflex.

The test does not try to use a stolen token. It reads the column and asks whether the stored value is the secret:

it('stores an api token as a hash, not in the clear', function () {
    $alice = owner();

    $this->actingAs($alice)->post('/tokens', ['name' => 'phone']);
    $plain = session('plain_token');

    $stored = DB::table('api_tokens')->where('user_id', $alice->id)->value('token_hash');
    expect($stored)->not->toBe($plain)->toBe(hash('sha256', $plain));
});
  ⨯ it stores an api token as a hash, not in the clear
  Failed: the stored value is identical to the token that was shown.

The fix is to store a hash and match on the hash:

$request->user()->apiTokens()->create(['name' => $data['name'], 'token_hash' => hash('sha256', $token)]);
$token = ApiToken::where('token_hash', hash('sha256', $bearer))->first();

A note on which transformation, because it is the heart of the cryptographic-failures category. A token is hashed, not encrypted, and the two are not interchangeable. Encryption is reversible: you encrypt something you will need to read back. Hashing is one-way: you hash something you only ever need to compare. The server never needs the original token again; it only needs to check whether a token someone presents matches one it issued, and a hash does that. Because the token is 48 random characters, a plain hash('sha256', …) is right here: there is nothing to brute-force, so the slow, salted password hashers are unnecessary. A password, which is short and human-chosen, needs Hash::make and its deliberate slowness; a 48-character random token needs only to be turned into something the database can hold without holding the secret. The lookup compares the full hash through the unique index, so a stolen database row is a hash, and a hash of a 48-character random string is not getting reversed. This is exactly what Sanctum does under its surface, and hand-rolling it once is how you come to trust that it does.

2. The password changed without the password

The profile page gets a change-password form. It validates the new password with the project's rules and saves it:

public function update(Request $request): RedirectResponse
{
    $data = $request->validate([
        'password' => ['required', 'confirmed', Password::defaults()],
    ]);

    $request->user()->update(['password' => $data['password']]);

    return back()->with('status', 'Password changed.');
}

The validation is thorough about the new password: twelve characters, confirmed, checked against the breach list. It asks nothing about the old one, and that is the gap. A change-password form that does not require the current password is not protecting the password; it is protecting the form. The attacker this matters for is not someone guessing, but someone who already has the session: a shared computer left signed in, a stolen session cookie, a borrowed laptop. For them, a password change without the current password is the step that turns temporary access into permanent access, because they set a password the real owner does not know and the owner's own password no longer works.

The test is that account takeover, as a request:

it('will not change a password without the current one', function () {
    $alice = User::factory()->create(['password' => 'the real password']);
    owner()->teams->first()->users()->attach($alice, ['role' => 'member']);

    $this->actingAs($alice)->put('/password', [
        'password' => 'a password an attacker chose', 'password_confirmation' => 'a password an attacker chose',
    ])->assertSessionHasErrors('current_password');

    expect(Hash::check('the real password', $alice->fresh()->password))->toBeTrue();
});
  ⨯ it will not change a password without the current one
  Failed asserting that false is true.

The last line is the account takeover: the real password no longer checks out, because the attacker's password replaced it. The fix is one validation rule, and Laravel ships it:

$data = $request->validate([
    'current_password' => ['required', 'current_password'],
    'password' => ['required', 'confirmed', 'different:current_password', Password::defaults()],
]);

The current_password rule checks the given value against the signed-in user's stored hash, so the change requires proving you are the owner now, not just that you were when the session began. This is re-authentication, and it belongs on every action that changes an authentication factor or does something irreversible: changing the password, changing the email the resets go to, disabling two-factor, deleting the account. different:current_password is a smaller courtesy: it stops a change that changes nothing. The reset flow from part 1 is the sibling of this and already correct, because proving control of the mailbox is its re-authentication; the signed-in change needs its own.

3. The second factor, and the secret behind it

Two-factor authentication is the feature that most tempts you to store a secret badly, because it has an actual secret to store: the seed the authenticator app and the server share, from which both compute the six-digit code. NoteMini adds TOTP, the time-based codes those apps show. The seed is generated when the user turns the feature on, confirmed with one code, and then needed on every login to check the code the user types.

The first thing to get right is where the seed lives. It is a secret, so the reflex from section 1 is to hash it, and that reflex is wrong here. The server needs the seed back, in full, every time it checks a code, because it recomputes the expected code from the seed and compares. A value you must read back is encrypted, not hashed. That is the distinction section 1 set up, now cutting the other way: the token is hashed because it is only ever compared; the seed is encrypted because it is used. Laravel's encrypted cast does it, tied to the application key:

protected function casts(): array
{
    return [
        // …
        'two_factor_secret' => 'encrypted',
    ];
}

The attack test turns the feature on and reads the raw column, the way a database dump would:

it('stores the two factor secret encrypted at rest', function () {
    $alice = owner();
    $this->actingAs($alice)->get('/two-factor');
    $secret = session('2fa.secret');
    $this->actingAs($alice)->post('/two-factor', ['code' => app(Totp::class)->at($secret, (int) floor(time() / 30))]);

    $raw = DB::table('users')->where('id', $alice->id)->value('two_factor_secret');
    expect($raw)->not->toContain($secret);
});
  ⨯ it stores the two factor secret encrypted at rest
  Expecting 'HF7QISIDZXNUGAGYTO3P7DLBH74NCY7Q' not to contain 'HF7QISIDZXNUGAGYTO3P7DLBH74NCY7Q'.

Without the cast, the seed is in the column in plain text: anyone who reads the row can generate the codes, which makes the second factor no factor at all. With the cast, the column holds ciphertext and the model hands back the seed in memory, decrypted with the app key, which lives in the environment and not in the database. A dump of the table is seeds nobody can use.

Two more things make the second factor real, and both are in the login challenge. The code check compares in constant time:

if (hash_equals($this->at($secret, $counter + $i), $code)) {
    return true;
}

hash_equals takes the same time whether the first character is wrong or the last, so the comparison does not leak, character by character through timing, how much of a guess was right. For a six-digit code the practical risk is small, but a comparison of secrets is the canonical place for a timing-safe check, and === on secret-dependent values is the habit worth not forming. The other thing is a limit. Six digits is a million possibilities, which is nothing to a script, so the challenge is rate-limited:

Route::post('/two-factor-challenge', [TwoFactorChallengeController::class, 'store'])
    ->middleware('throttle:5,1')->name('two-factor.challenge.store');
it('rate-limits the two factor challenge', function () {
    // …sign in with the right password, reaching the challenge
    foreach (range(1, 5) as $i) {
        $this->post('/two-factor-challenge', ['code' => '000000']);
    }
    $this->post('/two-factor-challenge', ['code' => '000000'])->assertStatus(429);
    $this->assertGuest();
});

Without the limit, a million guesses walks through the whole space in minutes and the second factor is a formality. The login itself is the two-step flow this implies: the password is checked with Auth::validate, which does not sign anyone in, and only a correct code completes the login:

if ($user->hasTwoFactorEnabled()) {
    $request->session()->regenerate();
    $request->session()->put('2fa.pending', $user->id);

    return redirect()->route('two-factor.challenge');
}

Auth::login($user, $request->boolean('remember'));

The order is the point: a right password with no code is a pending session that can see nothing, not a signed-in user who is asked for a code afterward.

What was already right

Three authentication weaknesses did not need a section, because part 1 built the app with them closed, and they are worth naming so the list feels complete. User enumeration: the sign-in form, the password-reset request and the team invite all give the same answer whether or not the address has an account, so none of them is a way to learn who has one. Session fixation: Auth::login is followed by session()->regenerate() everywhere a login happens, including after the two-factor challenge, so the session id a user carries after signing in is never one that was set before. Brute force on the password: the sign-in is rate-limited per email and address, which part 1 tested. The reset flow proves control of the mailbox before it changes anything, which is why section 2's signed-in change needed its own proof rather than inheriting one.

What is deliberately not here is anything about transport. Passwords and tokens travelling in clear text is the other half of cryptographic failures, and it is a property of how the app is served, not of its code: HTTPS, HSTS, the Secure flag on cookies. That is configuration, and configuration is the next part.

The results

  Tests:    26 passed (86 assertions)    # attack
  Tests:    36 passed (152 assertions)   # feature

Five new attack tests, from twenty-one to twenty-six. The feature suite grew more than usual, to thirty-six, because two-factor authentication is a real flow with a real happy path: turning it on, being asked for a code, completing with the right one. The ZAP baseline, signed in, spidered 78 URLs and reported the same nine header warnings and no failures. As in part 3, the baseline cannot see any of this: it has one session and reads what normal use produces, and none of the four weaknesses here shows in a response the spider would receive. A test that reads a column, on the other hand, sees a plaintext secret immediately, which is the argument for owning these as tests rather than hoping a scan will catch them.

What went wrong

The alias that was not registered. The API routes were given a new middleware, api.token, to accept a bearer token, and the alias was added to bootstrap/app.php, except the edit matched the wrong line and the alias never registered. Every API test failed with "Target class [api.token] does not exist", which is the framework saying it was handed a middleware name it has no class for. The fix was one line in the right place; the lesson is that a middleware alias is a two-part thing, the use at the route and the definition in the kernel, and a name with no definition fails loudly, which is the good kind of failure.

The filter that searched the wrong suite. Capturing the red output for each weakness meant turning a fix back off and running its one test, and the first attempt ran php artisan test --filter against the default suites, which are Unit and Feature; the attack tests are in the Attack suite, which the default run does not include, so every capture reported "No tests found" and looked, for a moment, like the vulnerabilities had healed themselves. The reds were real once the filter named the right suite. A test you cannot find is not a test that passes, and the two look identical from a distance.

Part 5 serves the application and asks what the server gives away: debug mode, the headers from parts 1 to 4 that the scanner has been flagging all along, the cookie flags, HTTPS, and the trust the app places in data that comes back to it: Security misconfiguration and data integrity: headers, debug mode, signed URLs and what the server reveals.

New posts by email

Get new posts by email. Nothing else, no digests, unsubscribe in one click.

Comments

Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.