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.