Consent

This site uses third party services that need your consent.

Skip to content
Steven Roland
  • Securing Your Laravel API with Passport: A Comprehensive Guide

    Laravel Passport is a powerful OAuth2 server implementation for Laravel applications. It provides a full OAuth2 server implementation out of the box, allowing you to secure your API and issue access tokens to your users. In this post, we'll explore how to set up Passport, its key features, and some practical use cases.

    Getting Started with Laravel Passport

    First, install Passport via Composer:

    composer require laravel/passport

    After installation, run the Passport migrations:

    php artisan migrate

    Next, install Passport:

    php artisan passport:install

    Configuring Passport

    Add the Laravel\Passport\HasApiTokens trait to your User model:

    use Laravel\Passport\HasApiTokens;
    
    class User extends Authenticatable
    {
        use HasApiTokens, Notifiable;
    }

    In your AuthServiceProvider, call the Passport::routes() method:

    use Laravel\Passport\Passport;
    
    public function boot()
    {
        $this->registerPolicies();
    
        Passport::routes();
    }

    Key Features and Examples

    Issuing Access Tokens

    Passport makes it easy to issue access tokens. Here's an example of a login endpoint:

    use Illuminate\Support\Facades\Auth;
    
    public function login(Request $request)
    {
        if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
            $user = Auth::user();
            $token = $user->createToken('MyApp')->accessToken;
    
            return response()->json(['token' => $token], 200);
        }
    
        return response()->json(['error' => 'Unauthorised'], 401);
    }

    Protecting Routes

    Protect your API routes using the auth:api middleware:

    Route::middleware('auth:api')->get('/user', function (Request $request) {
        return $request->user();
    });

    Scopes

    Define and assign scopes to control access to different parts of your API:

    Passport::tokensCan([
        'place-orders' => 'Place orders',
        'check-status' => 'Check order status',
    ]);

    Then, in your routes:

    Route::get('/orders', function () {
        // Access token has "place-orders" scope...
    })->middleware(['auth:api', 'scope:place-orders']);

    Personal Access Tokens

    Allow users to generate personal access tokens:

    $user = User::find(1);
    
    $token = $user->createToken('Token Name')->accessToken;

    Suggested Usages

    • Mobile Applications: Use Passport to secure the API for your mobile app.

    • Single Page Applications (SPAs): Implement OAuth2 authentication for your SPA.

    • Third-Party API Access: Allow third-party developers to access your API securely.

    • Microservices Architecture: Use Passport to secure communication between microservices.

    • IoT Devices: Implement secure authentication for IoT devices connecting to your API.

    Best Practices

    • Token Lifetimes: Configure appropriate lifetimes for your access and refresh tokens.

      Passport::tokensExpireIn(now()->addDays(15));
      Passport::refreshTokensExpireIn(now()->addDays(30));
    • Revoking Tokens: Implement token revocation when users log out.

      public function logout(Request $request)
      {
          $request->user()->token()->revoke();
      
          return response()->json(['message' => 'Successfully logged out']);
      }
    • Secure Your Clients: Keep your OAuth client secrets secure and never expose them in public repositories.

    • Use HTTPS: Always use HTTPS in production to protect token transmission.

    • Implement Refresh Tokens: Use refresh tokens to obtain new access tokens without requiring user credentials.

    Conclusion

    Laravel Passport provides a robust solution for API authentication in Laravel applications. By leveraging its features and following best practices, you can create secure, scalable APIs that support various authentication flows.

    Remember, while Passport offers powerful features out of the box, it's crucial to understand OAuth2 concepts and implement additional security measures appropriate for your specific use case. With proper implementation, Passport can significantly enhance the security and functionality of your Laravel API.

    More posts

    Living Fully: Embracing Life Beyond the Fear of Death

    Inspired by Natalie Babbitt's quote, this post explores the importance of living fully rather than fearing death. It offers insights on what constitutes a well-lived life and provides strategies for embracing each moment with authenticity and purpose.

    Supercharging Your Laravel Application with Octane

    Laravel Octane boosts application performance using high-powered servers like Swoole and RoadRunner. It offers features like pre-initialized workers, concurrent tasks, and a high-performance cache. Ideal for high-traffic websites, APIs, and real-time applications. Implement best practices like profiling your app and optimizing database queries for maximum benefit.

    Navigating Beliefs: The Quest for True Meaning

    Inspired by Chuck Palahniuk's quote, this post explores the challenge of believing in the right things and finding true meaning. It offers insights on critical thinking, questioning beliefs, and the importance of accurate interpretation in our quest for understanding.