Security

/laravel-agent:auth:setup

Setup authentication and authorization for your Laravel app

Overview

The /auth:setup command is an interactive wizard that helps you configure authentication and authorization for your Laravel application. It supports multiple authentication strategies including session-based, API tokens, OAuth2, and social login, along with robust authorization systems like roles and permissions.

Usage

/laravel-agent:auth:setup [preset]

Quick Presets

You can skip the interactive wizard by specifying a preset:

# Interactive wizard (recommended)
/laravel-agent:auth:setup

# API-only with Sanctum tokens
/laravel-agent:auth:setup api

# Single Page Application with Sanctum
/laravel-agent:auth:setup spa

# OAuth2 server with Passport
/laravel-agent:auth:setup oauth

# Social login with Socialite
/laravel-agent:auth:setup social

# Full setup with all authentication options
/laravel-agent:auth:setup full

Authentication Types

The wizard will guide you through selecting the right authentication type for your application:

Type Package Best For
Web Laravel Breeze/Fortify Traditional session-based web applications
API Laravel Sanctum Token-based authentication for mobile apps and APIs
SPA Laravel Sanctum Single Page Applications with CSRF protection
OAuth2 Laravel Passport Full OAuth2 server with client credentials, password, and authorization code grants

Authorization Systems

Choose how to handle roles and permissions:

System Package Features
Laratrust santigarcor/laratrust Teams + Roles + Permissions (complex multi-tenancy)
Spatie Permission spatie/laravel-permission Roles + Permissions (simple and elegant)
Policies Only Laravel built-in Resource-based authorization without roles

What Gets Configured

The command will automatically set up the following components based on your selections:

Component Description
Composer Packages Installs and configures required authentication packages
Controllers Generates authentication controllers (login, logout, register)
Routes Adds authentication routes to your application
Migrations Creates database tables for roles, permissions, and social providers
Seeders Generates seeders for default roles and permissions
Configuration Configures CORS, session settings, and API keys

Setup Process

The command follows a systematic process to configure your authentication:

1. Package Detection

First, the wizard checks which authentication packages are already installed:

# Checks for existing packages
laravel/sanctum
laravel/passport
laravel/fortify
santigarcor/laratrust
spatie/laravel-permission
socialiteproviders/manager

2. Authentication Type Selection

Choose the authentication strategy that fits your application:

  • Web - Session-based authentication using Breeze or Fortify
  • API - Token-based authentication using Sanctum
  • OAuth2 - Full OAuth2 server implementation using Passport
  • SPA - Single Page Application with Sanctum and CSRF protection

3. Authorization System Selection

Select how you want to handle permissions:

  • Laratrust - For complex apps requiring teams, roles, and permissions
  • Spatie Permission - For simpler role and permission management
  • Policies Only - Use Laravel's built-in authorization without packages

4. Social Login Configuration

Optionally enable social authentication providers:

  • Google OAuth
  • GitHub OAuth
  • Apple Sign In
  • Facebook Login
  • Twitter OAuth

5. Two-Factor Authentication

Enable 2FA for enhanced security using Laravel Fortify's built-in support.

6. Installation & Configuration

The wizard invokes the laravel-auth subagent to perform the actual setup:

# Example invocation
Action: setup
AuthType: api
Authorization: spatie
SocialProviders: [google, github]
Enable2FA: yes

Preset Examples

API Setup (/auth:setup api)

Perfect for mobile apps and API-only applications:

  • Installs Laravel Sanctum
  • Configures token authentication
  • Creates API authentication controller
  • Adds authentication routes: /api/login, /api/logout, /api/register
  • Sets up token-based middleware

SPA Setup (/auth:setup spa)

Ideal for Vue, React, or Angular single-page applications:

  • Installs Sanctum with CSRF protection
  • Configures cookie-based sessions
  • Sets up proper CORS configuration
  • Enables stateful API authentication
  • Configures SPA domain settings in sanctum.php

OAuth2 Setup (/auth:setup oauth)

Full OAuth2 server for third-party integrations:

  • Installs Laravel Passport
  • Configures client credentials grant
  • Sets up password grant
  • Enables authorization code grant
  • Creates OAuth clients table
  • Generates encryption keys

Social Setup (/auth:setup social)

Add social login to your application:

  • Installs Socialite and provider packages
  • Creates social authentication controller
  • Adds database migration for provider fields
  • Configures redirect URLs
  • Sets up provider-specific settings

Post-Setup Steps

After the wizard completes, you'll receive a detailed report with next steps:

Sample Output

## Authentication Configured

### Type
API (Laravel Sanctum)

### Packages Installed/Configured
- [x] laravel/sanctum
- [x] spatie/laravel-permission
- [x] socialiteproviders/manager

### Routes Added
- POST /api/login
- POST /api/logout
- POST /api/register
- GET /auth/google
- GET /auth/google/callback
- GET /auth/github
- GET /auth/github/callback

### Roles Created
- super-admin
- admin
- user

### Next Steps
1. Configure .env with API keys:
   - GOOGLE_CLIENT_ID=
   - GOOGLE_CLIENT_SECRET=
   - GITHUB_CLIENT_ID=
   - GITHUB_CLIENT_SECRET=
2. Run migrations: `php artisan migrate`
3. Seed permissions: `php artisan db:seed --class=RolesAndPermissionsSeeder`
4. Test authentication endpoints

Environment Configuration

Update your .env file with the required credentials:

# Sanctum Configuration
SANCTUM_STATEFUL_DOMAINS=localhost:3000,127.0.0.1:3000

# Social Login Providers
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_REDIRECT_URL=http://localhost/auth/google/callback

GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret
GITHUB_REDIRECT_URL=http://localhost/auth/github/callback

Database Migration

Run migrations to create the necessary tables:

php artisan migrate

Seed Roles and Permissions

Populate your database with default roles and permissions:

php artisan db:seed --class=RolesAndPermissionsSeeder

Example: API Authentication Controller

Sample controller generated for API authentication:

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
            'device_name' => 'required',
        ]);

        $user = User::where('email', $request->email)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'email' => ['The provided credentials are incorrect.'],
            ]);
        }

        return response()->json([
            'token' => $user->createToken($request->device_name)->plainTextToken,
            'user' => $user,
        ]);
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json(['message' => 'Logged out successfully']);
    }

    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'device_name' => 'required',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        return response()->json([
            'token' => $user->createToken($request->device_name)->plainTextToken,
            'user' => $user,
        ], 201);
    }

    public function user(Request $request)
    {
        return response()->json($request->user());
    }
}

Default Roles & Permissions

The command creates a standard role hierarchy:

Role Description Default Permissions
super-admin Full system access All permissions (*)
admin Administrative access manage-users, view-reports, edit-content
user Standard user access view-content, edit-own-profile

Best Practices

  1. Use Sanctum for SPAs - It provides CSRF protection and cookie-based authentication
  2. Enable rate limiting - Protect login endpoints from brute force attacks
  3. Store API keys securely - Never commit credentials to version control
  4. Use HTTPS in production - Essential for secure token transmission
  5. Implement 2FA - Add an extra layer of security for sensitive applications
  6. Follow principle of least privilege - Grant minimum permissions necessary

Related Agent

This command uses the laravel-auth subagent to perform the authentication setup.

See Also