Backend Development 2 min read 1,245 views

Building Secure APIs with Laravel 11: Authentication, Authorization, and Best Practices

A comprehensive guide to building production-ready, secure APIs with Laravel 11. Learn about Sanctum, rate limiting, input validation, and security best practices.

E
Code on computer screen

Laravel continues to be one of the most popular frameworks for building APIs, and version 11 brings even more tools for creating secure, performant backends. This guide covers everything from authentication setup to security best practices.

Setting Up Laravel Sanctum for API Authentication

Sanctum provides a lightweight authentication system perfect for SPAs and mobile applications:

// Install Sanctum
composer require laravel/sanctum

// Publish configuration
php artisan vendor:publish --provider="Laravel\\Sanctum\\SanctumServiceProvider"

// Run migrations
php artisan migrate

Implementing Token-Based Authentication

// app/Http/Controllers/AuthController.php
class AuthController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);

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

        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'message' => 'Invalid credentials'
            ], 401);
        }

        $token = $user->createToken('api-token')->plainTextToken;

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

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

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

Rate Limiting

Protect your API from abuse with Laravel's built-in rate limiting:

// app/Providers/RouteServiceProvider.php
protected function configureRateLimiting()
{
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by(
            $request->user()?->id ?: $request->ip()
        );
    });

    RateLimiter::for('auth', function (Request $request) {
        return Limit::perMinute(5)->by($request->ip());
    });
}

Input Validation and Sanitization

Always validate and sanitize input data:

// app/Http/Requests/CreateUserRequest.php
class CreateUserRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'unique:users'],
            'password' => ['required', 'min:8', 'confirmed'],
            'phone' => ['nullable', 'regex:/^[0-9+\-\s]+$/'],
        ];
    }

    public function messages()
    {
        return [
            'email.unique' => 'This email is already registered.',
        ];
    }
}

Security Best Practices

  1. Always use HTTPS: Force SSL in production
  2. Implement CORS properly: Restrict allowed origins
  3. Hash passwords: Use bcrypt or Argon2
  4. Sanitize output: Prevent XSS attacks
  5. Use prepared statements: Laravel does this automatically
  6. Implement audit logging: Track sensitive operations

CORS Configuration

// config/cors.php
return [
    'paths' => ['api/*'],
    'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:3000')],
    'allowed_methods' => ['*'],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

API Versioning

// routes/api.php
Route::prefix('v1')->group(function () {
    Route::apiResource('users', UserController::class);
    Route::apiResource('posts', PostController::class);
});

Route::prefix('v2')->group(function () {
    Route::apiResource('users', V2\UserController::class);
});

Building secure APIs requires attention to detail and following established patterns. Laravel provides excellent tools—use them wisely.

Share this article:
ES

Written by Edrees Salih

Full-stack software engineer with 9 years of experience. Passionate about building scalable solutions and sharing knowledge with the developer community.

View Profile

Comments (0)

Leave a Comment

Your email will not be published.

No comments yet. Be the first to share your thoughts!