FusionAuth QuickStart for Laravel
On this page
This QuickStart explains how to add a login page and authentication to a website built with Laravel. You'll begin with a simple Laravel app that allows visitors to edit a file. Then, you'll add authentication to the app with a FusionAuth instance. Finally, you'll extend the app to handle multiple independent users with user data provided by FusionAuth.
This tutorial should take between 5 and 15 minutes; less if you already have prerequisites like Docker installed.
Prerequisites#
This QuickStart requires:
If you use macOS or Windows, you need one of the following container management tools:
- Docker Desktop
- OrbStack (to use OrbStack for
docker composecommands after installation, rundocker context use orbstack) - Podman (in the commands below, replace
dockerwithpodman)
Create a Simple Laravel App#
For this QuickStart, we'll use a Laravel app that reads and writes data to a text file:
-
Create a Laravel project in a folder named
laravel-quickstart:$ composer create-project laravel/laravel=13.11.0 laravel-quickstartComposer installs Laravel, creates a
.envconfiguration file, and sets up a SQLite database that Laravel uses to store sessions. -
Navigate into the project folder:
$ cd laravel-quickstart -
Replace the contents of
routes/web.phpwith the following code:<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Route; Route::get('/', function () { $path = base_path('note.txt'); return view('notes', ['note' => File::exists($path) ? File::get($path) : '']); }); Route::post('/', function (Request $request) { File::put(base_path('note.txt'), $request->input('content', '')); return redirect('/'); });The
GETroute reads the note when the page loads, and thePOSTroute saves the note when the form is submitted. -
In the
resources/viewsfolder, create a file namednotes.blade.phpwith the following code, which displays the note in a form:<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Notes</title> </head> <body> <h1>Notes</h1> <form method="post" action="/"> @csrf <label for="content">Your note</label><br> <textarea id="content" name="content" rows="8" cols="40">{{ $note }}</textarea><br> <button type="submit">Save Changes</button> </form> </body> </html>The form includes
@csrfbecause Laravel rejects form submissions without a token that prevents CSRFAn attack in which a malicious site makes the user's browser send an unwanted request to a site where the user is logged in. The OAuth 2.0stateparameter protects the authorization flow from CSRF.. -
Run the app:
$ php artisan serve --port=3000 -
Open the app at http://localhost:3000.
-
Type "Hello Laravel" in the text area, then click Save Changes .
-
In a file browser or terminal, look in the
laravel-quickstartfolder. You should see a new file namednote.txt, with text content "Hello Laravel". -
Press Ctrl+C on your keyboard to stop the app.
Install and Run FusionAuth#
Before we can add authentication to our Laravel app, we need a local FusionAuth instance:
-
Open your container management tool (listed in the prerequisites above).
-
From the
laravel-quickstartfolder, clone the GitHub repository for the FusionAuth instance you'll use with this QuickStart:$ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git -
Navigate into the cloned directory:
$ cd fusionauth-quickstart-app -
To start a local instance of FusionAuth, run the following command (omit the
-dflag to see all Docker logs):$ docker compose up -d -
Wait until all networks, volumes, and containers show a green status of Healthy, Started, or Created. This may take a few minutes, depending on your network speed and cached dependencies.
-
Open http://localhost:9011/admin to access the FusionAuth Admin UI.
-
Log in with these credentials:
- Login:
admin@example.com - Password:
password
- Login:
-
Navigate to Applications . In the QuickStart App row, click Select -> Edit , then click the OAuth tab. On this page, you can find your client Id and client secret, and set redirect and logout URLs. In the next part of this QuickStart, we'll use these values to connect our Laravel app with FusionAuth.
-
Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Laravel app, and because FusionAuth supports SSO, we need to log out of our admin account before we can log in as a normal user.
Add FusionAuth to the Laravel App#
Now that you have a working instance of FusionAuth and a working Laravel app, let's use FusionAuth to add login to your Laravel app:
-
Navigate out of the
fusionauth-quickstart-appfolder, back to thelaravel-quickstartfolder that containsartisanandnote.txt:$ cd .. -
Install Laravel Socialite and the FusionAuth provider for Socialite, which handle communication with our FusionAuth instance:
$ composer require laravel/socialite:5.33.0 socialiteproviders/fusionauth:5.0.3 -
Add the following lines to the end of the
.envfile (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI):FUSIONAUTH_BASE_URL=http://localhost:9011 FUSIONAUTH_CLIENT_ID=f0510a74-da7a-4101-a474-05e7f1d5ba7e FUSIONAUTH_CLIENT_SECRET=super-secret-secret-that-should-be-regenerated-for-production FUSIONAUTH_REDIRECT_URI=http://localhost:3000/oauth-callback -
In
config/services.php, add the following entry at the end of the returned array, before the closing];. The entry passes the values from.envto Socialite:'fusionauth' => [ 'base_url' => env('FUSIONAUTH_BASE_URL'), 'client_id' => env('FUSIONAUTH_CLIENT_ID'), 'client_secret' => env('FUSIONAUTH_CLIENT_SECRET'), 'redirect' => env('FUSIONAUTH_REDIRECT_URI'), ], -
Replace the contents of
app/Providers/AppServiceProvider.phpwith the following code, which adds the FusionAuth provider to Socialite:<?php namespace App\Providers; use Illuminate\Support\Facades\Event; use Illuminate\Support\ServiceProvider; use SocialiteProviders\FusionAuth\Provider; use SocialiteProviders\Manager\SocialiteWasCalled; class AppServiceProvider extends ServiceProvider { public function boot(): void { Event::listen(function (SocialiteWasCalled $event) { $event->extendSocialite('fusionauth', Provider::class); }); } } -
Replace the contents of
routes/web.phpwith the following code:<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Route; use Laravel\Socialite\Facades\Socialite; Route::get('/login', function () { return view('login'); }); Route::get('/login/start', function () { return Socialite::driver('fusionauth')->enablePKCE()->redirect(); }); Route::get('/oauth-callback', function (Request $request) { $user = Socialite::driver('fusionauth')->enablePKCE()->user(); $request->session()->regenerate(); $request->session()->put('user', ['id' => $user->getId()]); return redirect('/'); }); Route::post('/logout', function (Request $request) { $request->session()->invalidate(); return redirect(config('services.fusionauth.base_url').'/oauth2/logout?'.http_build_query([ 'client_id' => config('services.fusionauth.client_id'), 'post_logout_redirect_uri' => url('/login'), ])); }); Route::get('/', function (Request $request) { if (! $request->session()->has('user')) { return redirect('/login'); } $path = base_path('note.txt'); return view('notes', ['note' => File::exists($path) ? File::get($path) : '']); }); Route::post('/', function (Request $request) { if (! $request->session()->has('user')) { return redirect('/login'); } File::put(base_path('note.txt'), $request->input('content', '')); return redirect('/'); });The new code connects the app to FusionAuth:
- The
/login/startroute sends the user to the FusionAuth login page.enablePKCE()turns on PKCEAn extension to OAuth 2.0 that mitigates authorization code interception attacks using dynamic code verifiers and challenges., so a stolen authorization code is useless on its own. - The
/oauth-callbackroute receives the authorization code from FusionAuth. Socialite exchanges the code for an access token and uses the token to fetch the user's details from FusionAuth's UserInfo endpoint. The app then stores the user's Id in the Laravel session. - The
/logoutroute clears the Laravel session, then sends the user to FusionAuth's/oauth2/logoutendpoint so the FusionAuth session ends too. FusionAuth then sends the user back to/login. - The
/routes send users who aren't logged in to/login.
- The
-
In the
resources/viewsfolder, create a file namedlogin.blade.phpwith the following code, which links to/login/start:<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Log in</title> </head> <body> <h1>Log in to Notes</h1> <a href="/login/start">Log in with FusionAuth</a> </body> </html> -
Replace the contents of
resources/views/notes.blade.phpwith the following code, which adds a Logout button:<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Notes</title> </head> <body> <h1>Notes</h1> <form method="post" action="/"> @csrf <label for="content">Your note</label><br> <textarea id="content" name="content" rows="8" cols="40">{{ $note }}</textarea><br> <button type="submit">Save Changes</button> </form> <form method="post" action="/logout"> @csrf <button type="submit">Logout</button> </form> </body> </html> -
Run the app, which now uses FusionAuth login:
$ php artisan serve --port=3000 -
Open the app at http://localhost:3000 and click Log in with FusionAuth .
-
Log in with the following credentials:
- Login:
richard@example.com - Password:
password
- Login:
-
Edit and save the note in the authenticated Laravel app.
-
Click Logout . FusionAuth ends your session and sends you back to the login page.
Add Independent Notes for Each User#
To see a more realistic example of FusionAuth usage, we can improve the app even more, so every user gets a unique note to edit. To accomplish this, we'll use FusionAuth's user data:
-
Open the FusionAuth Admin UI at http://localhost:9011/admin.
-
Log in with the following credentials:
- Login:
admin@example.com - Password:
password
- Login:
-
Navigate to Applications . In the QuickStart App row, click Select -> Edit , then click the Registration tab.
- Under Self-service registration, check that Registration mode is set to Create registration. The QuickStart configuration has already turned on self-service registration.
- In the Registration field list, turn on the Enabled and Required switches for the following rows:
- Birthdate
- First name
- Last name
-
Click Save in the top right of the page to save your changes to self-service registration.
-
Navigate to Users . In the Richard Hendricks row, click Select -> Manage .
-
In the Source tab, look for the
firstNameandlastNamefields. That's what we'll use to personalize the UI for each user. We'll use the user'sidfield to generate a unique name for each user's note. -
Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Laravel app.
-
Replace the contents of
routes/web.phpwith the following code, which stores the user's name (first and last) and Id in the session, and stores each user's note in a separate file:<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Route; use Laravel\Socialite\Facades\Socialite; Route::get('/login', function () { return view('login'); }); Route::get('/login/start', function () { return Socialite::driver('fusionauth')->enablePKCE()->redirect(); }); Route::get('/oauth-callback', function (Request $request) { $user = Socialite::driver('fusionauth')->enablePKCE()->user(); $request->session()->regenerate(); $request->session()->put('user', [ 'id' => $user->getId(), 'name' => $user->getName() ?: 'writer', ]); return redirect('/'); }); Route::post('/logout', function (Request $request) { $request->session()->invalidate(); return redirect(config('services.fusionauth.base_url').'/oauth2/logout?'.http_build_query([ 'client_id' => config('services.fusionauth.client_id'), 'post_logout_redirect_uri' => url('/login'), ])); }); Route::get('/', function (Request $request) { $user = $request->session()->get('user'); if (! $user) { return redirect('/login'); } $path = base_path("user_data/note-{$user['id']}.txt"); return view('notes', [ 'name' => $user['name'], 'note' => File::exists($path) ? File::get($path) : "Write a note, {$user['name']}.", ]); }); Route::post('/', function (Request $request) { $user = $request->session()->get('user'); if (! $user) { return redirect('/login'); } File::ensureDirectoryExists(base_path('user_data')); File::put(base_path("user_data/note-{$user['id']}.txt"), $request->input('content', '')); return redirect('/'); });The FusionAuth provider requests the
profilescope by default, so the UserInfo response already includes the user's first and last name.getName()returns the full name. -
Replace the contents of
resources/views/notes.blade.phpwith the following code, which greets the user by name:<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Notes</title> </head> <body> <h1>Welcome, {{ $name }}</h1> <form method="post" action="/"> @csrf <label for="content">Your note</label><br> <textarea id="content" name="content" rows="8" cols="40">{{ $note }}</textarea><br> <button type="submit">Save Changes</button> </form> <form method="post" action="/logout"> @csrf <button type="submit">Logout</button> </form> </body> </html> -
Open the app at http://localhost:3000 and click Log in with FusionAuth . The development server loads the changed files on each request, so you don't need to restart it.
-
Log in with the following credentials:
- Login:
richard@example.com - Password:
password
- Login:
-
In a separate private or incognito window, open the app at http://localhost:3000 and click Log in with FusionAuth .
-
Click Create an account and create an account using your personal email address, a password, your name, and your birthdate.
-
Edit and save your own note. Your name appears at the top of the page and in the default note text.
Your Laravel app now provides unique notes for each user. Each user can independently edit and save their note. When a user saves a note, the app writes the note to a note-<id>.txt file in the user_data directory. To identify which note belongs to which user, compare the id in the file name with the id field in the user's Source tab in the Admin UI. Log out of the app before you open the Admin UI. Otherwise, FusionAuth single sign-on logs you in to the Admin UI as the app user, who doesn't have access to the Admin UI.
Summary#
In this QuickStart, FusionAuth handled login for your Laravel app:
- Socialite sent users to the FusionAuth login page and exchanged the authorization code for tokens, so the app never saw their passwords.
- The session check in the
/routes kept logged-out users away from the notes page. - FusionAuth gave the app each user's unique Id and name. The app used the Id to keep each note separate and the name to greet the user.
- FusionAuth's self-service registration let new users create their own accounts, with no sign-up code in the app.
Next Steps#
This was a quick introduction to using FusionAuth for user authentication. To learn more about integrating FusionAuth with your product, see Get Started.
FusionAuth has many features (including Social Login, Single Sign-On, Passkeys, Multi-factor Authentication), most of which are free. This example app is a great starting point for learning about FusionAuth features.