Skip to content

09. Authentication & Authorization

Daniel Trolezi edited this page Sep 26, 2024 · 3 revisions

Here are some of my experiments with authentication and authorization.

Starter Packs

Laravel provides different authentication starter packs to get you started fast.

Jetstream

Jetstream provides the implementation for your application's login, registration, email verification, two-factor authentication, session management, API via Laravel Sanctum, and optional team management features.

You can choose between Livewire and Inertia to build the interface.

Example:
🌱 feature/jetstream

Relevant Commits:

See also:

Sanctum (auth:sanctum)

Sactum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / scopes which specify which actions the tokens are allowed to perform.

Example:
🌱 feature/sanctum

Relevant Commits:

See also:

Web Guard (auth:web)

Session-Based Authentication:
The web guard uses session-based authentication, which means it relies on sessions and cookies to maintain the authentication state. When a user logs in, Laravel stores their information in the session, and the user's session cookie is used to identify them on subsequent requests.

Intended for Traditional Web Applications:
This guard is primarily used in traditional web applications where you have users interacting with a web interface, logging in through forms, and maintaining a session across multiple requests.

Features:

  • Supports CSRF protection, which is essential for web forms.
  • Provides features like "remember me"
  • Can redirect users after login or when they attempt to access a restricted page.

Middleware:
The web guard is often associated with the auth middleware, which ensures that users are authenticated before accessing specific routes.

Example

# Using GET for testing purposes
Route::get('/login', function(Request $request) {
    $credentials = [
        'email'    => 'root@localhost',
        'password' => 'secret'
    ];

    if(Auth::attempt($credentials)){
        $request->session()->regenerate();
        return Auth::user();
    }

    return 'Login failed';
})->middleware('guest');

Route::get('/logout', function(Request $request) {
    Auth::logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();

    return 'Logged out';
})->middleware('auth');

Route::get('/auth-web', function() {
    return Auth::user()->toArray();
})->middleware('auth:web');

HTTP Basic

Basic Middleware (auth.basic)

Although HTTP Basic Auth is meant to be stateless, Laravel will automatically store a session cookie after login when using auth.basic.

It automatically prompts the browser for credentials if they are not provided and checks them against the database.

⚠️ After the first time, the browser will cache the credentials so You won't need to pass them again even after loggin out, unless you clear you browser data.

You can also set the Authorization header to authenticate.

Example

Route::get('/auth-basic', function() {
    return Auth::user()->toArray();
})->middleware('auth.basic');

Basic Once Middleware

In case you need Basic Auth to be stateless, create a custom middleware as described here: Stateless HTTP Basic Authentication

HTTP Basic Authentication:
This is a simple authentication method where the user's credentials (username and password) are sent with each request in the Authorization header.

Intended for API or Simple Authentication:
This guard is typically used in API contexts or in simple cases where you don't want to manage sessions. It is stateless, meaning it does not rely on sessions or cookies and does not maintain any state between requests.

Features:

  • Does not support "remember me" functionality.
  • Does not involve redirects; if authentication fails, it simply returns a 401 Unauthorized response.
  • It is more straightforward but less secure than other methods since credentials are sent with every request (though they should be over HTTPS).

JWT

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.

Authorization is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.

Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.

I'm using the package firebase/php-jwt to handle JWT tokens in PHP.

Example:
📁 danieltrolezi/gamewatch

Relevant Commits: