Why Choose WorkOS AuthKit for Laravel 12 Authentication?
Why Choose WorkOS AuthKit for Laravel 12 Authentication?
However, for teams that need enterprise-grade features without building everything from scratch, WorkOS AuthKit offers a compelling alternative. WorkOS is a developer-friendly platform that simplifies authentication and other features like SSO, passkeys, and advanced social logins. It provides a hosted authentication platform with flexible, secure integration.
Here are some reasons why WorkOS is a great choice for Laravel 12 authentication:
- Enterprise-Ready: Supports SSO (SAML), SCIM, RBAC, and more.
- Social Logins: Google, Microsoft, GitHub, Apple out of the box.
- Additional Features: Passkeys, Magic Auth (email codes), rate limiting, and geographical protection.
- Seamless Laravel Integration: Built into Laravel 12 starter kits with no manual OAuth handling.
Compared to built-in options:
- Vs. Sanctum/Passport: WorkOS handles token management and revocations automatically.
- Vs. Socialite: Pre-configured providers with less code.
- Security: Built-in MFA and brute-force protection.

Table Of Content
1 Prerequisites
- PHP 8.3+
- Composer
- Node.js/NPM
- MySQL or SQLite database
- WorkOS account (free tier available at workos.com – create an app to get CLIENT_ID and API_KEY)
2 Introduction
Authentication is the backbone of any web application that manages user data. Getting it right means protecting sensitive information, preventing unauthorized access, and providing a seamless login experience. Laravel 12 makes this easier than ever with its updated starter kits and first-party package ecosystem.
While Laravel offers built-in solutions like Laravel Sanctum for API token and SPA authentication, Laravel Passport for full OAuth2 server implementation, and Laravel Socialite for integrating social login providers, third-party solutions like WorkOS AuthKit can offer additional features and flexibility. This is especially valuable for applications that need to support enterprise SSO, passwordless authentication, or multiple identity providers without building custom integrations.
In this tutorial, we will walk through setting up a fresh Laravel 12 project with WorkOS AuthKit using the React + Inertia.js starter kit. By the end, you will have a working authentication system with social logins, passkeys, and enterprise-ready SSO capabilities.
3 Create a Fresh Laravel 12 Project
3.1 Create the Laravel Project
# Install Laravel installer if not already
composer global require laravel/installer
# Create new app (during prompts: select React, WorkOS, Pest for testing)
laravel new my-auth-app
# Navigate to project
cd my-auth-app
# Install dependencies
composer install
npm install
# Generate app key
php artisan key:generate
During laravel new, you will be prompted to choose:
- Stack: React (uses Inertia.js for server-driven SPA routing)
- Authentication: WorkOS (configures the WorkOS SDK and callback routes)
- Testing: Pest (or PHPUnit, based on your preference)
This generates the full boilerplate with WorkOS integration, including pre-configured controllers, middleware, React pages, and environment variable placeholders. The starter kit also installs the laravel/workos Composer package automatically.
3.2 Configure Environment
Edit .env file (create from .env.example if needed):
APP_NAME=MyAuthApp
APP_ENV=local
APP_KEY=base64:your-generated-key
APP_DEBUG=true
APP_URL=http://localhost:8000
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=sqlite # or mysql, etc.
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=your_db
# DB_USERNAME=root
# DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
WORKOS_CLIENT_ID=client_XXXXXXXXXXXXXXXXXXXX
WORKOS_API_KEY=sk_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
WORKOS_REDIRECT_URL=http://localhost:8000/authenticate
Replace WORKOS_CLIENT_ID and WORKOS_API_KEY with your values from WorkOS dashboard. Set up redirects in WorkOS dashboard:
- Sign-in callback: http://localhost:8000/authenticate
- Homepage: http://localhost:8000/
- Logout: http://localhost:8000/
Disable "Email + Password" in WorkOS dashboard if desired (under Authentication settings).
4 Create Migration for Users Table
php artisan migrate
Key migration file: database/migrations/2014_10_12_000000_create_users_table.php (auto-generated, but here's the content for completeness):
<?php
// database/migrations/YYYY_MM_YY_000000_create_users_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('workos_id')->unique()->nullable(); // Added for WorkOS
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable(); // Nullable if using passwordless
$table->rememberToken();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('users');
}
};
User Model (app/Models/User.php)
This uses the HasWorkOS trait (provided by laravel/workos package, included in starter kit).
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\WorkOS\Concerns\HasWorkOS; // Trait for WorkOS integration
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable, HasWorkOS;
protected $fillable = [
'name',
'email',
'workos_id', // Stores WorkOS user ID
];
protected $hidden = [
'password',
'remember_token',
];
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}
The HasWorkOS trait likely includes methods like findOrCreateFromWorkOS($profile) to handle user creation/sync from WorkOS callbacks.
5 Create Custom Auth Controller
php artisan make:controller Auth/AuthenticatedSessionController
Edit app/Http/Controllers/Auth/AuthenticatedSessionController.php to extend or customize the default authentication flow:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class AuthenticatedSessionController extends Controller
{
/**
* Handle the WorkOS callback after authentication.
*/
public function callback(Request $request)
{
// Validate the authorization code from WorkOS
$code = $request->input('code');
if (!$code) {
return redirect('/login')->withErrors(['auth' => 'Authorization code missing.']);
}
// Exchange code for user profile via WorkOS SDK
$userProfile = \WorkOS\AuthKit::getUserProfile($code);
Log::info('WorkOS authentication successful for: ' . $userProfile->email);
// Find existing user or create from WorkOS profile
$user = User::findOrCreateFromWorkOS($userProfile);
Auth::login($user);
return redirect('/dashboard');
}
/**
* Log the user out and invalidate the session.
*/
public function destroy(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
Note: The WorkOS starter kit handles most of this automatically. Only create a custom controller if you need additional logic such as logging, role assignment, or redirecting users based on their profile attributes.
6 Frontend Code (React with Inertia)
Login Page (resources/js/Pages/Auth/Login.tsx)
import React from 'react';
import { Head, Link, useForm } from '@inertiajs/react';
import GuestLayout from '@/Layouts/GuestLayout';
import PrimaryButton from '@/Components/PrimaryButton';
export default function Login({ status, canResetPassword }: { status?: string, canResetPassword: boolean }) {
const handleWorkOSLogin = () => {
window.location.href = '/auth/redirect'; // Redirects to WorkOS
};
return (
<GuestLayout>
<Head title="Login" />
{status && <div className="mb-4 font-medium text-sm text-green-600">{status}</div>}
<div className="mt-6">
<PrimaryButton onClick={handleWorkOSLogin} className="w-full">
Login with WorkOS (Social/Passkeys/Magic Auth)
</PrimaryButton>
</div>
{/* Add links for password reset if enabled */}
{canResetPassword && (
<Link
href={route('password.request')}
className="underline text-sm text-gray-600 hover:text-gray-900"
>
Forgot your password?
</Link>
)}
</GuestLayout>
);
}
The starter kit includes GuestLayout, PrimaryButton, etc.
7 Define Routes
The starter kit sets this up. Here's the relevant part:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\AuthenticatedSessionController;
// WorkOS redirect route
Route::get('/auth/redirect', function () {
return redirect(\WorkOS\AuthKit::getAuthorizationUrl()); // Redirects to WorkOS hosted auth
})->name('auth.redirect');
// Protected routes
Route::middleware('auth')->group(function () {
Route::get('/dashboard', function () {
return inertia('Dashboard'); // Or view('dashboard')
})->name('dashboard');
});
8 Folder Structure
9 Run & Test the Application
Start the development servers in two separate terminal windows:
# Terminal 1: Compile frontend assets with hot reload
npm run dev
# Terminal 2: Start Laravel development server
php artisan serve
Visit http://localhost:8000/login in your browser. Click the login button to be redirected to WorkOS for authentication. After successful login with your chosen provider (Google, GitHub, Microsoft, etc.), you will be redirected back to /dashboard.
Troubleshooting Tips:
- If you see a redirect error, verify that WORKOS_REDIRECT_URL in your .env matches the callback URL configured in your WorkOS dashboard.
- Ensure your database migrations have run successfully with php artisan migrate:status.
- Check storage/logs/laravel.log for detailed error messages if authentication fails.
10 Conclusion
WorkOS AuthKit provides a powerful, secure, and developer-friendly way to manage authentication in Laravel 12 applications. With built-in support for SSO (SAML), social logins (Google, Microsoft, GitHub, Apple), passkeys, Magic Auth, MFA, and brute-force protection, it significantly reduces the complexity of implementing enterprise-grade authentication.
Key Takeaways:
- Laravel 12 starter kits make WorkOS integration seamless with zero manual OAuth configuration.
- WorkOS handles token management, session revocation, and provider configuration automatically.
- The free tier is suitable for most projects, scaling as your user base grows.
- For API-only apps, consider combining WorkOS with Laravel Sanctum for token-based API auth.
For Laravel developers seeking to integrate multiple authentication options seamlessly without managing complex OAuth flows, WorkOS AuthKit is a fantastic tool to consider. Check the official WorkOS documentation for advanced configuration options.
Related Laravel 12 Tutorials
If you found this WorkOS AuthKit tutorial helpful, explore these related Laravel 12 guides to deepen your development skills:
- Build APIs: Once authentication is in place, learn How to Build a REST API in Laravel 12 with step-by-step examples for creating secure, authenticated API endpoints.
- Background Processing: Scale your authenticated app with the Laravel 12 Queue and Jobs Tutorial to handle email verification and notifications asynchronously.
- Routing & Middleware: Understand how authentication middleware protects your routes in our Laravel 12 Routing and Middleware Complete Guide.
- Performance: After setting up auth, optimize your app with Laravel 12 Performance Tips for Lightning-Fast Loading.
- Eloquent ORM: Master database queries for your user models with Laravel 12 Eloquent Tips and Tricks for Beginners.
- Upgrading: Moving from an older version? Check out How to Upgrade from Laravel 11 to Laravel 12 Without Breaking Changes.
- Debugging: Running into issues? Our guide on Common Laravel 12 Errors and How to Fix Them covers the most frequent problems developers face.
Written by Revathi M
PHP Developer & Technical Writer · 10+ years building web applications with CodeIgniter and Laravel
Revathi specializes in PHP backend development, authentication systems, and REST API design. She writes practical, production-tested tutorials at Get Sample Code to help developers build secure applications faster.
Frequently Asked Questions
WorkOS AuthKit is a hosted authentication platform that simplifies integrating enterprise-grade authentication features into your application. It handles SSO (SAML/OIDC), social logins (Google, Microsoft, GitHub, Apple), passkeys, Magic Auth (email-based passwordless login), MFA, and brute-force protection. In Laravel 12, it integrates directly through the official starter kit, requiring minimal configuration.
The easiest way is to use the Laravel 12 starter kit by running laravel new my-app and selecting WorkOS as the authentication provider during setup. This automatically installs the laravel/workos package and configures the necessary routes and controllers. You then add your WORKOS_CLIENT_ID, WORKOS_API_KEY, and WORKOS_REDIRECT_URL to your .env file from your WorkOS dashboard.
Yes, WorkOS supports OAuth-based authentication with multiple identity providers including Google, Microsoft, GitHub, Apple, and Okta. It also supports SAML-based SSO for enterprise use cases, making it suitable for both consumer and business applications.
SSO (Single Sign-On) allows users to authenticate once and gain access to multiple applications without logging in again. WorkOS enables SSO integration by supporting both SAML and OIDC protocols. You configure your identity provider (like Okta, Azure AD, or Google Workspace) in the WorkOS dashboard, and WorkOS handles the authentication flow and returns the user profile to your Laravel application.
Yes, WorkOS is built with security as a core focus. It offers multi-factor authentication (MFA), brute-force protection with rate limiting, geographical login restrictions, and follows industry security standards. All authentication flows use HTTPS, and WorkOS undergoes regular security audits. For enterprise customers, it also supports SCIM provisioning and RBAC.
