Hand-rolled login

Login form

A login form posts an email and a password to a route that handles the check. The Blade template below shows the only fields such a form needs.

The csrf directive adds a hidden token that protects the form from cross site request forgery.

<form method="POST" action="/login"> @csrf <input type="email" name="email"> <input type="password" name="password"> <button type="submit">Log in</button> </form>

Auth::attempt

The attempt method compares the given credentials with the users table and logs the visitor in on success. It hashes the given password and compares it with the stored hash behind the scenes.

The method returns true when the credentials match and false otherwise, so the controller can branch on the result.

use Illuminate\Support\Facades\Auth; $credentials = $request->validate([ "email" => "required|email", "password" => "required|string", ]); if (Auth::attempt($credentials)) { $request->session()->regenerate(); }

Regenerate session

After a successful login the session id must change so an old id cannot be reused by an attacker. The regenerate method gives the session a fresh id while keeping its data.

Always call it right after attempt succeeds, before any redirect to the account area.

$request->session()->regenerate(); return redirect()->intended("/home");

Logout

Logout reverses the process in three steps: log out of the guard, drop all session data, and refresh the csrf token. Skipping any step leaves a half closed session behind.

Send the visitor to the welcome page or the login form after the session is clean.

use Illuminate\Support\Facades\Auth; Auth::logout(); $request->session()->invalidate(); $request->session()->regenerateToken();

Next: Middleware

Article author: Arthur Isaev