Laravel Tutorial Advanced

Implementing OAuth2 Authentication in Laravel


OAuth2 is an industry-standard protocol for authorization, enabling secure API access for third-party applications. In Laravel, you can easily implement OAuth2 authentication using the popular Laravel Passport package.

Step 1: Install Laravel Passport

Begin by installing Laravel Passport through Composer:

composer require laravel/passport

After installation, run the migration command to create the necessary tables:

php artisan migrate

Next, run the Passport install command:

php artisan passport:install

This will create encryption keys and necessary database tables for Passport.

Step 2: Configuration

Configure your User model to implement the

HasApiTokens
trait:

// app/Models/User.php
use LaravelPassportHasApiTokens;
class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
    // ...
}

Then, in your

config/auth.php
file, ensure that the API guard is using Passport:

// config/auth.php
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Step 3: Create OAuth2 Clients

Create OAuth2 clients to represent the third-party applications that will access your API:

php artisan passport:client --password

This command will generate client ID and secret for your OAuth2 clients.

Step 4: Protecting Routes with OAuth2

Protect your API routes by adding the

auth:api
middleware:

// routes/api.php
Route::middleware('auth:api')->group(function () {
    // Your protected API routes here
});

Step 5: Requesting OAuth2 Tokens

Third-party applications can request access tokens by making a POST request to the Laravel OAuth2 token endpoint:

POST /oauth/token
grant_type=password
client_id={client-id}
client_secret={client-secret}
username={user-email}
password={user-password}
scope=

The server will respond with an access token and a refresh token, allowing the third-party application to make authenticated requests to your API.

Step 6: Revoking Tokens

Implement token revocation to allow users to log out and invalidate access tokens:

POST /oauth/token/revoke
token={access-token}

This will revoke the access token and, if applicable, the refresh token.

Conclusion

Congratulations! You've successfully implemented OAuth2 authentication in Laravel using Passport. This provides a secure way for third-party applications to access your API on behalf of users.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.