Blog

Laravel Authentication: Getting Started and HTTP Auth Tutorial

laravel authentication

What Is Laravel Authentication? 

Laravel is a PHP web application framework which includes authentication built into it. The framework aims to simplify the many steps and tools it traditionally took to build a modern fullstack web application, including adding a basic level of security for users. The built-in authentication of Laravel automates tasks like handling login, registration, password reset, and session management, allowing developers to focus on building application features. Laravel achieves this through its syntax and built-in functionalities that address most standard authentication requirements.

Laravel’s authentication system integrates with its routing and templating systems, providing a cohesive development experience. Its configuration files and controllers help manage user sessions, handle login events, and ensure that only authenticated users can access protected routes. This saves time for developers and helps secure applications.

In this article:

Types of Laravel Authentication methods 

There are several types of authentication supported by Laravel.

Password-based authentication

Password-based authentication is the most common method in Laravel. It involves users providing a username and password combination to access the application. Laravel provides features to handle user registration, login, and password resets.

The process relies on the users table, which stores hashed passwords using the bcrypt hashing algorithm by default. During authentication, Laravel compares the hashed password in the database with the hash of the password provided by the user. 

To make use of these capabilities, install the laravel/ui package using composer: 

composer require laravel/ui

Then run the following command:

php artisan ui:auth

This scaffolding sets up views, controllers, and routes needed for password-based authentication, making the implementation process secure. Developers can customize this behavior by adjusting the corresponding controller methods or modifying the authentication views.

Token-based authentication

Token-based authentication in Laravel is commonly used for APIs where a token is issued to the client upon successful authentication. This token is then passed with a request when requiring authentication, typically in the Authorization header, allowing the server to verify the user’s identity.

Laravel supports token-based authentication through its Laravel Sanctum and Laravel Passport packages:

  • Laravel Sanctum is for simpler use cases, such as single-page applications (SPAs) or mobile apps, providing an easy way to manage API tokens with minimal setup.
  • Laravel Passport offers a more feature-rich OAuth 2 implementation, suitable for large-scale applications that require advanced authentication flows, such as client credentials or authorization codes.

Tokens issued by either package are stored securely and can be revoked when necessary, ensuring that only authorized users can interact with the API.

Multi-factor authentication

Multi-factor Authentication (MFA) adds an extra layer of security by requiring users to authenticate via different factors, such as a password, biometric, or one-time password (OTP) sent via email, SMS, or generated by an authenticator app. This improves security by making it more challenging for malicious agents to compromise different methods.

Laravel supports MFA by integrating with packages such as Laravel Fortify or third-party solutions. Laravel Fortify provides support for two-factor authentication (2FA), allowing users to enable and configure MFA from their account settings. Once activated, users will be prompted to enter the OTP during the login process after providing their password.

With these additional security measures, Laravel ensures that applications remain protected against common threats like phishing and brute-force attacks.

Setting up authentication in Laravel 

Here’s a walkthrough of how to get started with Laravel authentication. The instructions in this section and the tutorial below are adapted from the Laravel documentation.

Installing a starter kit

To quickly set up authentication in a new Laravel application, it is recommended to use a starter kit. Laravel provides two main starter kits:

  • Laravel Breeze is a minimal setup that implements essential authentication features such as login, registration, password reset, and email verification. It uses Blade templates styled with Tailwind CSS and supports optional scaffolding with Livewire or Inertia, giving developers the flexibility to choose between Vue.js or React for the front end.
  • Laravel Jetstream is a more comprehensive solution. It offers features like two-factor authentication (2FA), teams, profile management, API support with Laravel Sanctum, and more. Like Breeze, Jetstream also supports scaffolding with Livewire or Inertia.

To install one of these starter kits, run the following Artisan command:

composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate

This command sets up the authentication system, generates the necessary routes, views, and controllers, and prepares the Laravel application for user authentication.

Retrieving an authenticated user

Once authentication is set up, admins often need to retrieve the authenticated user for various operations, such as accessing user-specific data. Laravel provides a few simple methods to do this.

  1. You can retrieve the authenticated user using the Auth facade:

use Illuminate\Support\Facades\Auth;
$user = Auth::user();

2. Alternatively, within controller methods, you can access the authenticated user via the Illuminate\Http\Request object. This can be done by type-hinting the Request object in the controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller  
{  
    public function profile(Request $request)  
    {  
        // Retrieve the authenticated user from the request  
        $user = $request->user(); 
        // Return user-specific data  
        return view('profile', compact('user'));  
    }  
}

Verifying that the current user Is authenticated

To check if a user is authenticated, use the check method provided by the Auth facade. This method returns true if a user is authenticated, and false otherwise:

<?php

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // The current user is logged in
    // Display current user information
} else {
    // The user is not logged in
    // Display a welcome message for a guest
}

Let’s logout and try to access this page again:

Securing routes

Laravel allows admins to protect routes by ensuring that only authenticated users can access them. This is done by applying the auth middleware to routes. For example, to restrict access to a route, use the middleware method:

Route::get('/dashboard', function () {
  // Only authenticated users can access the route
})->middleware('auth');

If an unauthenticated user attempts to access a protected route, they will be automatically redirected to the login page.

Additionally, admins can specify different authentication guards by passing the guard name to the middleware. This is useful when there are multiple user types (e.g., admins, users):

Route::get('/admin', function () {
  // Only authenticated admins can access the route
})->middleware('auth:admin');

Tutorial: HTTP basic authentication in Laravel

Laravel offers built-in support for HTTP basic authentication, a simple way to authenticate users without the need for a custom login page or session handling. Instead, users are prompted to enter their credentials through the browser’s default authentication dialog. This method is useful for quick, stateless authentication, such as in APIs or administrative routes where a full authentication system may not be necessary.

Attaching the basic authentication middleware

Laravel makes it easy to set up HTTP basic authentication by using the auth.basic middleware, which is included by default. This can be applied to any route, and Laravel will automatically prompt users to enter their credentials when accessing that route:

Route::get('/profile', function () {
  // Only authenticated users can access the route
})->middleware('auth.basic');

In this example, when a user tries to access the /profile route, the browser prompts for a username and password. Laravel assumes the email column in the users table serves as the username by default.

Stateless HTTP Basic authentication

In situations where you don’t want Laravel to manage sessions, such as API requests, you can implement stateless HTTP basic authentication. This method verifies credentials without setting session cookies, making it suitable for RESTful APIs where each request should be independently authenticated.

1. To achieve this, you can create a custom middleware that uses the onceBasic method, which handles the authentication without maintaining session state:

<?php

namespace App\Http\Middleware;

use Closure;  
use Illuminate\Http\Request;  
use Illuminate\Support\Facades\Auth;  
use Symfony\Component\HttpFoundation\Response;

class AuthenticateOnceWithBasicAuth  
{  
    /**  
     * Handle incoming requests.  
     *  
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return \Symfony\Component\HttpFoundation\Response
     */  
    public function handle(Request $request, Closure $next): Response  
    {  
        return Auth::onceBasic() ?: $next($request);  
    }  
}

2. Once you’ve created this middleware, apply it to routes where stateless authentication is required:

Route::get('/api/user', function () {
// Only authenticated users can access the route
})->middleware(AuthenticateOnceWithBasicAuth::class);

With this setup, the /api/user route will prompt for credentials, and Laravel will authenticate the request without storing any session data, making it suitable for stateless API endpoints.

Best practices for secure authentication in Laravel 

Here are some best security practices that help ensure strong authentication mechanisms within Laravel applications. 

Regularly updating dependencies

Keeping Laravel and its packages up to date is critical for maintaining secure authentication. Laravel’s ecosystem evolves rapidly, and security patches are frequently released to address vulnerabilities in the core framework and its dependencies. To regularly check for updates, use Composer:

composer update

It’s essential to review the change logs and upgrade guides provided by Laravel to understand how new updates might impact your application. Automated tools like Laravel Shift can also assist in upgrading projects to the latest version.

Enforcing HTTPS and secure cookies

All authentication-related traffic should be transmitted over HTTPS to prevent man-in-the-middle (MITM) attacks. Laravel makes enforcing HTTPS simple through its AppServiceProvider class, where admins can enforce SSL by using the following code in the boot method:

if (app()->environment('production')) {
\URL::forceScheme('https');
}

Additionally, enabling the secure flag on cookies ensures that cookies are only sent over HTTPS connections. Admins can configure this in config/session.php by setting:

'secure' => env('SESSION_SECURE_COOKIE', true),

This prevents session hijacking by ensuring that session cookies are never transmitted in plain text.

Secure session management

Laravel offers several session drivers, such as file, cookie, database, and Redis, but the database or Redis drivers are typically preferred for larger applications, as they provide better control and scalability.

Configuring the session timeout and lifetime settings appropriately in config/session.php helps to reduce the risk of session fixation or hijacking. For example, setting a reasonable session expiration with the lifetime option:

'lifetime' => 120, // in minutes

Enabling session encryption in Laravel is another essential step to securing session data. This can be done by setting:

'encrypt' => true,

This ensures that session data is stored in an encrypted format, making it much harder for attackers to decipher in case of a breach.

Monitoring and auditing authentication processes

Continuous monitoring of authentication events is vital for identifying suspicious activities, such as brute force attempts or unauthorized logins. Laravel provides built-in logging functionality, which can be enhanced by configuring login event listeners to track login attempts, password changes, or failed logins.

Tools like Laravel Telescope or third-party solutions like Sentry can be used to monitor and log authentication-related actions in real-time. These tools help in auditing user actions, identifying potential security breaches, and alerting developers to unusual activities.

User education and security awareness

Even the most secure authentication system can be compromised by poor user practices, such as weak passwords or falling for phishing attacks. Educating users about creating strong passwords, recognizing phishing attempts, and enabling 2FA can significantly improve the security of an application.

Administrators can enforce password complexity rules by customizing the Validator class during user registration and provide clear instructions to users when enabling 2FA through Laravel Fortify or third-party MFA packages. 

Laravel SSO with Frontegg 

Frontegg is a user management solution with full support for Laravel. Once you integrate Frontegg’s self-served user management solution, your customers can configure their SSO completely on their own with just a few lines of code. The single sign-on can be integrated with IDPs with commonly-used protocols like OIDC and SAML. Yes, you can implement social login SSOs as well. The front end has been taken care of as well. 

You can leverage all of Frontegg’s SSO components and personalize your SaaS offering with a login box builder. This embeddable box reduces implementation times as no in-house development is required. Users can authenticate smoothly and gain quick access to the app, without waiting for product updates and fixes. A true end-to-end SSO solution for SaaS apps and services.

Learn more about Frontegg for authentication