Authentication Done Right

matt
Matthew Gros · Dec 28, 2025

TLDR

Sessions for traditional web apps, JWTs for APIs, OAuth for third-party auth. Always hash passwords, use HTTPS, implement rate limiting.

Authentication Done Right

Authentication Methods

Each has its place. Pick based on your use case.

Sessions (Traditional Web Apps)

// Login
if (Auth::attempt(['email' => $email, 'password' => $password])) {
    $request->session()->regenerate();
    return redirect('/dashboard');
}

// Check auth
if (Auth::check()) {
    $user = Auth::user();
}

// Logout
Auth::logout();
$request->session()->invalidate();

Pros: Simple, built-in CSRF protection, easy to invalidate Cons: Requires session storage, not great for APIs

JWTs (APIs, Mobile Apps)

// Generate token
$token = JWT::encode([
    'sub' => $user->id,
    'exp' => time() + 3600
], $secretKey, 'HS256');

// Verify token
$decoded = JWT::decode($token, new Key($secretKey, 'HS256'));

Pros: Stateless, works across domains Cons: Can't easily revoke, larger than session cookies

OAuth 2.0 (Third-Party Auth)

Use Laravel Socialite:

// Redirect to provider
return Socialite::driver('google')->redirect();

// Handle callback
$user = Socialite::driver('google')->user();

Security Essentials

  1. Hash passwords - Use bcrypt or Argon2
  2. HTTPS everywhere - No exceptions
  3. Rate limiting - Prevent brute force
  4. Secure cookies - HttpOnly, Secure, SameSite flags
// Rate limiting
Route::middleware(['throttle:5,1'])->group(function () {
    Route::post('/login', [AuthController::class, 'login']);
});

About the Author

matt

I build and ship automation-driven products using Laravel and modern frontend stacks (Vue/React), with a focus on scalability, measurable outcomes, and tight user experience. I’m based in Toronto, have 13+ years in PHP, and I also hold a pilot’s license. I enjoy working on new tech projects and generally exploring new technology.