search
HomePHP FrameworkLaravelLaravel development: How to implement API OAuth2 authentication using Laravel Passport?

As the use of APIs becomes more and more popular, protecting the security and scalability of APIs becomes increasingly critical. OAuth2 has become a widely adopted API security protocol that allows applications to access protected resources through authorization. To implement OAuth2 authentication, Laravel Passport provides a simple and flexible way. In this article, we will learn how to implement API OAuth2 authentication using Laravel Passport.

Laravel Passport is an officially provided OAuth2 server library that can easily add OAuth2 authentication to your Laravel application. It provides API authentication for clients of the Laravel framework, protecting APIs and restricting resource access through tokens. With a few configuration steps, you can create a secure OAuth2 server and provide authentication and authorization for your API.

In order to start using Laravel Passport, you need to install it. You can install it through the Composer package manager:

composer require laravel/passport

Once you have Laravel Passport installed, you need to run migrations to create the necessary database tables:

php artisan migrate

In order to enable Laravel Passport, you need to register ServiceProvider and middleware. Add the following ServiceProvider and middleware in the config/app.php file:

'providers' => [
    // ...
    LaravelPassportPassportServiceProvider::class,
],

'middleware' => [
    // ...
    LaravelPassportHttpMiddlewareCreateFreshApiToken::class,
],

Laravel Passport requires a "keys" table for issuing access tokens and refresh tokens. Running the following command will generate this table:

php artisan passport:install

This will create an encrypted RSA key pair for signing and verifying tokens, as well as a client named "personal_access_client" and a client named "password_client" client. These two clients are used to create different types of tokens. The first client is used to generate personal access tokens that allow the client to access any API endpoint secured with OAuth2 authentication. The second client is used to create password authorization tokens that allow the client to obtain an access token via username and password.

In this process, you also need to configure Laravel Passport in your config/auth.php file. You need to add the passport driver to the API guard so that Laravel Passport can handle everything related to OAuth2. An example is as follows:

'guards' => [
    // ...
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Now that we have completed the setup, we can start creating API routes and controllers.

First, you need to define the API route. For example, let's say you have an API endpoint to get a list of tasks:

Route::get('/tasks', 'TaskController@index')->middleware('auth:api');

Next, you need to create a controller to handle the request and respond to the tasks:

class TaskController extends Controller
{
    public function index()
    {
        $tasks = Task::all();

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

In the middleware method add " auth:api" parameter to instruct us to use API guards to protect routes.

Now let's see how to perform OAuth2 authentication and get access token. You need to create a client that will authorize the OAuth2 flow using the password to obtain the access token. This way you can authenticate on the API endpoint with API requests.

You can create a new client in Laravel Passport's client list, or use the Passport::client() method in your code to generate a random client id and client secret for the client. You can save the client id and client secret in your .env file or you can provide them directly in your Passport::client() method. This method will create a new client and return the client id and client secret:

use LaravelPassportClient;
use IlluminateSupportFacadesDB;

$client = $this->createClient();

public function createClient()
{
    $client = Client::forceCreate([
        'user_id' => null,
        'name' => 'Test Client',
        'secret' => str_random(40),
        'redirect' => '',
        'personal_access_client' => false,
        'password_client' => true,
        'revoked' => false,
    ]);

    DB::table('oauth_client_grants')->insert([
        'client_id' => $client->id,
        'grant_id' => 1,
    ]);

    return $client;
}

Now that we have a client, we need to use Laravel Passport in the controller to get the access token and use it to access protected API endpoints. We need to implement OAuth2 authentication in the controller using the following code:

use IlluminateSupportFacadesAuth;
use LaravelPassportClientRepository;

class TaskController extends Controller
{
    protected $clients;
    
    public function __construct(ClientRepository $clients)
    {
        $this->clients = $clients;
    }

    public function index()
    {
        $client = $this->clients->find(2);

        $response = $this->actingAsClient($client, function () {
            return $this->get('/api/tasks');
        });

        return $response->getContent();
    }

    protected function actingAsClient($client, $callback, $scopes = [])
    {
        $proxy = new LaravelPassportHttpControllersAccessTokenController();

        $token = $proxy->issueToken(
            $this->getPersonalAccessTokenRequest($client, $scopes)
        );

        Auth::guard('web')->loginUsingId($client->user_id);

        $callback($token);

        return $this->app->make(IlluminateHttpRequest::class);
    }

    protected function getPersonalAccessTokenRequest($client, $scopes = [])
    {
        $data = [
            'grant_type' => 'client_credentials',
            'client_id' => $client->id,
            'client_secret' => $client->secret,
            'scope' => implode(' ', $scopes),
        ];

        return IlluminateHttpRequest::create('/oauth/token', 'POST', $data);
    }
}

Using the actingAsClient() method we can simulate running the request as a client and any method in the controller can use this method for OAuth2 Authentication. We need to pass a client object, a callback function to perform the API request, and optionally the permissions to add to the request.

Now that we have completed the OAuth2 authentication configuration for Laravel Passport, we can easily implement secure OAuth2 authentication on our API endpoints by using the above code pattern. Passport is a relatively new project. However, it is perfectly integrated with Laravel and provides multiple OAuth2 authentication services, allowing you to easily add authentication and authorization to your API. If you are running a Laravel application and need to add OAuth2 authentication, Laravel Passport is ideal for this purpose.

The above is the detailed content of Laravel development: How to implement API OAuth2 authentication using Laravel Passport?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Beyond the Zoom Call: Creative Strategies for Connecting Distributed TeamsBeyond the Zoom Call: Creative Strategies for Connecting Distributed TeamsApr 26, 2025 am 12:24 AM

ToenhanceengagementandcohesionamongdistributedteamsbeyondZoom,implementthesestrategies:1)Organizevirtualcoffeebreaksforinformalchats,2)UseasynchronoustoolslikeSlackfornon-workdiscussions,3)Introducegamificationwithteamgamesorchallenges,and4)Encourage

What are the breaking changes in the latest Laravel version?What are the breaking changes in the latest Laravel version?Apr 26, 2025 am 12:23 AM

Laravel10introducesseveralbreakingchanges:1)ItrequiresPHP8.1orhigher,2)TheRouteServiceProvidernowusesabootmethodforloadingroutes,3)ThewithTimestamps()methodonEloquentrelationshipsisdeprecated,and4)TheRequestclassnowpreferstherules()methodforvalidatio

The Productivity Paradox: Maintaining Focus and Motivation in Remote SettingsThe Productivity Paradox: Maintaining Focus and Motivation in Remote SettingsApr 26, 2025 am 12:17 AM

Tomaintainfocusandmotivationinremotework,createastructuredenvironment,managedigitaldistractions,fostermotivationthroughsocialinteractionsandgoalsetting,maintainwork-lifebalance,anduseappropriatetechnology.1)Setupadedicatedworkspaceandsticktoaroutine.

Building Trust from Afar: Fostering Collaboration in Distributed EnvironmentsBuilding Trust from Afar: Fostering Collaboration in Distributed EnvironmentsApr 26, 2025 am 12:13 AM

Tofostercollaborationandtrustinremoteteams,implementthesestrategies:1)Establishregular,structuredcommunicationwithpersonalcheck-ins,2)Usecollaborativetoolsfortransparency,3)Recognizeandcelebrateachievements,and4)Fosteracultureoftrustandadaptability.

What are the key features of the latest Laravel version?What are the key features of the latest Laravel version?Apr 26, 2025 am 12:01 AM

Laravel's latest version of the main features include: 1. LaravelOctane improves application performance, 2. Improved model factory support relationships and state definitions, 3. Enhanced Artisan commands, 4. Improved error handling, 5. New Eloquent accessors and modifiers. These features significantly improve development efficiency and application performance, but need to be used with caution to avoid potential problems.

The Illusion of Inclusion: Addressing Isolation and Loneliness in Remote WorkThe Illusion of Inclusion: Addressing Isolation and Loneliness in Remote WorkApr 25, 2025 am 12:28 AM

Tocombatisolationandlonelinessinremotework,companiesshouldimplementregular,meaningfulinteractions,provideequalgrowthopportunities,andusetechnologyeffectively.1)Fostergenuineconnectionsthroughvirtualcoffeebreaksandpersonalsharing.2)Ensureremoteworkers

Laravel for Full-Stack Development: A Comprehensive GuideLaravel for Full-Stack Development: A Comprehensive GuideApr 25, 2025 am 12:27 AM

Laravelispopularforfull-stackdevelopmentbecauseitoffersaseamlessblendofbackendpowerandfrontendflexibility.1)Itsbackendcapabilities,likeEloquentORM,simplifydatabaseinteractions.2)TheBladetemplatingengineallowsforclean,dynamicHTMLtemplates.3)LaravelMix

Video Conferencing Showdown: Choosing the Right Platform for Remote MeetingsVideo Conferencing Showdown: Choosing the Right Platform for Remote MeetingsApr 25, 2025 am 12:26 AM

Key factors in choosing a video conferencing platform include user interface, security, and functionality. 1) The user interface should be intuitive, such as Zoom. 2) Security needs to be paid attention to, and Microsoft Teams provides end-to-end encryption. 3) Functions need to match requirements, GoogleMeet is suitable for short meetings, and CiscoWebex provides advanced collaboration tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.