Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 67 ยท Authentication and Authorization

Registering, Logging In and Out

Build login, registration and logout in Laravel: Auth::attempt, Auth::login, remember me, session regeneration, password hashing, login throttling and the auth middleware.

Registration, login and logout look simple: create a user, check a password, remember the result. The details are what keep accounts safe: hash passwords properly, regenerate the session id at login so an attacker can't plant one, throttle guessing attempts, and invalidate everything at logout. Laravel does the heavy lifting in a handful of methods on the Auth facade.

If you used a starter kit (Authentication Overview and Starter Kits), this code was already generated for you. Reading it by hand once teaches you what that generated code does and where you would change it. You'll write the controller code as real Laravel (read-only here) and rebuild the key behaviors, remember-me, session fixation protection and throttling, as runnable PHP stand-ins.

Registering a user

Registration has three jobs: validate the input, store a user with a hashed password, and log them in. Validation is covered in Validation; here is the controller:

PHP
namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RegisterController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:12', 'confirmed'],
        ]);

        $user = User::create($validated);

        Auth::login($user);
        $request->session()->regenerate();

        return redirect()->route('dashboard');
    }
}

There is no Hash::make() call. A new Laravel User model declares a cast that hashes the password for you:

PHP
protected function casts(): array
{
    return [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];
}

With the hashed cast, assigning $user->password = 'secret' stores a bcrypt hash (the default driver; Argon2 is configurable in config/hashing.php, and the cost is tuned there too). The cast leaves values that already look like a hash alone. You can still call Hash::make($plain), Hash::check($plain, $hash) and Hash::needsRehash($hash) yourself; they are thin wrappers over the same ideas as PHP's password_hash() family explained in Password Hashing. Laravel's Auth::attempt() even rehashes a password at login when your configured cost has changed.

The password column must be long enough for any hash (the default migration uses a string of 255 characters). Never store, log or email a plain-text password.

Logging in with Auth::attempt

Auth::attempt() takes an array of credentials and does the whole check: it finds the user through the provider by every key except password, then compares the password against the stored hash.

PHP
public function store(Request $request): RedirectResponse
{
    $credentials = $request->validate([
        'email' => ['required', 'email'],
        'password' => ['required'],
    ]);

    if (Auth::attempt($credentials, $request->boolean('remember'))) {
        $request->session()->regenerate();

        return redirect()->intended(route('dashboard'));
    }

    return back()->withErrors([
        'email' => 'These credentials do not match our records.',
    ])->onlyInput('email');
}

Several details are worth slowing down for:

  • The second argument is "remember me". When true, Laravel sets a long-lived "recaller" cookie holding the user id and a token stored in the remember_token column, so the user stays signed in after the session ends.
  • session()->regenerate() issues a fresh session id after login. Without it, an attacker who made you use a session id they know (session fixation) would share your logged-in session.
  • redirect()->intended() sends the user back to the page that made them log in (the auth middleware stores it), or to the fallback if there was none.
  • One error message for both cases. The text doesn't reveal whether the email exists. See Web Security Basics for why that matters.
  • Extra conditions go in the array: Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1]) only accepts active users. Never put the password hash in the array.

Related methods you will meet: Auth::login($user, $remember) logs in a user you already have (after registration or a social login), Auth::loginUsingId(1) is handy in tests and tinker, Auth::once($credentials) authenticates for a single request without session or cookie (useful for tiny API endpoints), and Auth::viaRemember() tells you whether the current login came from the remember cookie.

sequenceDiagram
    participant B as Browser
    participant C as LoginController
    participant G as Session guard
    participant P as Eloquent provider
    B->>C: POST /login (email, password, remember)
    C->>G: Auth::attempt(credentials, remember)
    G->>P: retrieve user by email
    P-->>G: user and password hash
    G->>G: Hash::check(password, hash)
    G-->>C: true, session now holds the user id
    C->>C: session()->regenerate()
    C-->>B: 302 to the intended page

A login: the provider finds the user, the guard verifies the hash and writes the id to the session, then the controller regenerates the session id.

Logging out

Logout must do three things: forget the user, throw away the session data, and rotate the CSRF token so a stale form can't be reused.

PHP
public function destroy(Request $request): RedirectResponse
{
    Auth::logout();

    $request->session()->invalidate();
    $request->session()->regenerateToken();

    return redirect('/');
}

Wire it to a POST route (a link would let any page log you out through an image tag) and send the CSRF token from a form. See Forms, CSRF and Assets with Vite. If you want to log a user out of every device, Auth::logoutOtherDevices($password) re-hashes the stored password so other sessions stop matching (it needs the auth.session middleware on your routes).

Protecting routes

Two middleware aliases do most of the work: auth lets only logged-in users through, and guest lets only visitors through (so a logged-in user visiting the login page is redirected away).

PHP
Route::middleware('guest')->group(function () {
    Route::get('/login', [LoginController::class, 'create'])->name('login');
    Route::post('/login', [LoginController::class, 'store']);
    Route::get('/register', [RegisterController::class, 'create']);
    Route::post('/register', [RegisterController::class, 'store']);
});

Route::middleware('auth')->group(function () {
    Route::get('/dashboard', DashboardController::class)->name('dashboard');
    Route::post('/logout', [LoginController::class, 'destroy']);
});

The route named login is where auth sends guests. You can change the redirect targets in bootstrap/app.php with $middleware->redirectGuestsTo(...) and redirectUsersTo(...). In Blade, @auth ... @endauth and @guest ... @endguest do the same decision for pieces of markup. Middleware in general is explained in Middleware.

Session fixation, in code

The session-id rotation sounds abstract, so make it concrete. The stand-in below keeps a "server" with sessions keyed by id. The vulnerable login keeps the same id; the safe login moves the data to a new id and destroys the old one. The ids are produced by a counter here so the output is stable; real ones are long random strings.

PHP Why login regenerates the session id

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In the vulnerable run, the attacker's pre-login id suddenly belongs to user 42. In the safe run the old id no longer exists, so the same trick gets the attacker nothing. This is exactly what the one line $request->session()->regenerate() buys you.

Throttling login attempts

A login form without limits invites password guessing. Laravel's RateLimiter counts hits per key for a window of time, and the standard pattern keys by email plus IP address:

PHP
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;

$key = Str::transliterate(Str::lower($request->input('email')).'|'.$request->ip());

if (RateLimiter::tooManyAttempts($key, 5)) {
    $seconds = RateLimiter::availableIn($key);

    throw ValidationException::withMessages([
        'email' => "Too many attempts. Try again in {$seconds} seconds.",
    ]);
}

if (! Auth::attempt($credentials, $request->boolean('remember'))) {
    RateLimiter::hit($key);       // counts for 60 seconds by default
    // ... return back with errors
}

RateLimiter::clear($key);         // success resets the counter

If you use Fortify (and so the starter kits), this is already built in, with a named limiter you can tweak. The stand-in below shows the core logic with a controllable clock, so you can watch the lockout open and close.

PHP A login throttle with a fake clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Three wrong guesses fill the bucket, and even the correct password is refused while the lock lasts, which is the point: the attacker can't tell whether a guess was right. Once the hits expire, the correct password works and clears the counter. Caching drivers back the real limiter (Caching).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the login code call $request->session()->regenerate() after a successful Auth::attempt()?

    An attacker who forced a known session id on the victim would otherwise share their logged-in session. A fresh id makes the old one useless.
  2. 2. What does the second argument of Auth::attempt($credentials, true) do?

    The boolean means "remember". Laravel sets a recaller cookie so the user stays signed in after the session expires.
  3. 3. With the hashed cast on the User model, what happens when you run User::create(['password' => 'secret-passphrase', ...])?

    The cast hashes the value when it is assigned. Passwords are hashed (one way), never encrypted, so nobody can read them back.
  4. 4. Which steps belong in a correct logout?

    Forgetting the user, discarding the session data and rotating the token together ensure nothing from the old session can be reused.
  5. 5. Why should a failed login show the same message whether the email or the password was wrong?

    Different messages let attackers enumerate registered emails. One generic message keeps that information private.

Summary

  • Registration validates input, creates the user (the hashed cast hashes the password), calls Auth::login() and regenerates the session.
  • Auth::attempt($credentials, $remember) looks the user up by every key except password and verifies the hash; follow it with session()->regenerate() and redirect()->intended().
  • Logout is Auth::logout() + session()->invalidate() + regenerateToken(), sent as a POST with CSRF protection.
  • Use the auth and guest middleware (and @auth / @guest in Blade) to guard routes and pages.
  • Regenerating the session id defeats session fixation; throttling (RateLimiter::hit, tooManyAttempts) slows password guessing; use one generic error message.
  • Starter kits and Fortify implement all of this for you; the runnable examples here are stand-ins that show the logic.

Next: Fortify, Email Verification and Password Reset