Home >PHP Framework >Laravel >Laravel development: How to implement API OAuth2 authentication using Laravel Passport?

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

WBOY
WBOYOriginal
2023-06-13 23:13:54980browse

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