laravel-auth

Auto-invoked skill

Setup authentication with policies, gates, roles, Sanctum

Trigger Keywords

This skill automatically activates when Claude detects these keywords:

auth login permission policy gate sanctum role

Overview

The laravel-auth skill provides expertise for implementing authentication and authorization. It covers Laravel's built-in auth, Sanctum for APIs, policies for model authorization, and role-based access control.

What This Skill Provides

  • Authentication - Session-based, token-based, social login
  • Authorization - Policies, gates, middleware
  • Sanctum - SPA authentication and API tokens
  • Roles & Permissions - Spatie or custom implementations
  • Multi-tenancy - Tenant isolation patterns
  • 2FA - Two-factor authentication setup

Example Conversations

# Setting up auth
"Set up authentication for my SPA using Sanctum"

# Authorization policies
"Create a policy so users can only edit their own posts"

# Role-based access
"Implement admin, editor, and viewer roles with different permissions"

# API authentication
"How do I protect my API routes with Sanctum tokens?"

Policy Example

<?php

namespace App\Policies;

use App\Models\Post;
use App\Models\User;

class PostPolicy
{
    // Runs before all other checks
    public function before(User $user, string $ability): ?bool
    {
        if ($user->isAdmin()) {
            return true; // Admins can do anything
        }
        return null; // Continue to specific check
    }

    public function view(User $user, Post $post): bool
    {
        return $post->published || $user->id === $post->user_id;
    }

    public function update(User $user, Post $post): bool
    {
        return $user->id === $post->user_id;
    }

    public function delete(User $user, Post $post): bool
    {
        return $user->id === $post->user_id
            && $post->comments()->count() === 0;
    }
}

// Usage in controller
public function update(Request $request, Post $post)
{
    $this->authorize('update', $post);
    // ...
}

Gate vs Policy

Use When
Gates Simple actions not tied to a model (e.g., "access admin panel")
Policies Model-specific authorization (CRUD on Post, User, etc.)

Sanctum API Authentication

// Creating a token with abilities
$token = $user->createToken('api-token', ['posts:read', 'posts:write']);

// Protecting routes
Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user', fn () => auth()->user());
});

// Checking token abilities
if ($user->tokenCan('posts:write')) {
    // User can write posts
}

// In controller
public function store(Request $request)
{
    if (!$request->user()->tokenCan('posts:write')) {
        abort(403);
    }
}

Encrypted Model Attributes

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

final class User extends Model
{
    // Using built-in cast
    protected function casts(): array
    {
        return [
            'api_key' => 'encrypted',
            'settings' => 'encrypted:array',
        ];
    }
}

// Manual encryption
use Illuminate\Support\Facades\Crypt;

$encrypted = Crypt::encryptString($sensitive);
$decrypted = Crypt::decryptString($encrypted);

Common Pitfalls

// 1. Storing Plain Passwords - Always use Hash
// BAD
$user->password = $request->password;

// GOOD
$user->password = Hash::make($request->password);

// 2. No Policy Registration - Register in AuthServiceProvider
protected $policies = [
    Post::class => PostPolicy::class,
];

// 3. Missing Middleware - Protect routes
Route::middleware('auth')->group(function () {
    // Protected routes
});

// 4. Token Exposure - Never log tokens
// BAD
Log::info('Token: ' . $token->plainTextToken);

// 5. No Rate Limiting - Rate limit login attempts
Route::post('/login', [AuthController::class, 'login'])
    ->middleware('throttle:5,1');

// 6. Session Fixation - Regenerate session after login
$request->session()->regenerate();

Package Integration

  • laravel/sanctum - API token authentication
  • laravel/passport - Full OAuth2 server
  • spatie/laravel-permission - Role & permission management
  • laravel/fortify - Authentication backend

Best Practices

  • Use policies for model authorization
  • Use gates for general abilities
  • Rate limit authentication endpoints
  • Use HTTPS in production
  • Regenerate session after login
  • Implement proper logout

Authorization Middleware

// In routes
Route::put('/posts/{post}', [PostController::class, 'update'])
    ->middleware('can:update,post');

// Or in controller constructor
public function __construct()
{
    $this->authorizeResource(Post::class, 'post');
}

Related Commands

Related Agent