How To Create A OAuth And OpenID Connect (OIDC) Authentication In Laravel

Laravel module that utilizes the league/oauth2-client library to handle OAuth and OpenID Connect (OIDC) authentication.

First, install the required dependency by running composer require league/oauth2-client in your Laravel project directory.

Next, create a new file called AuthProvider.php in the app directory with the following contents:

				
					<?php

namespace App;

use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Provider\GenericProvider;

class AuthProvider
{
    private $provider;
    private $clientId;
    private $clientSecret;
    private $redirectUri;
    private $scopes;

    public function __construct()
    {
        $this->clientId = 'your-client-id'; // Client ID registered with the identity provider
        $this->clientSecret = 'your-client-secret'; // Client secret registered with the identity provider
        $this->redirectUri = 'http://localhost:8000/callback'; // Callback URL after authentication
        $this->scopes = ['openid', 'profile', 'email']; // Requested scopes

        $this->provider = new GenericProvider([
            'clientId' => $this->clientId,
            'clientSecret' => $this->clientSecret,
            'redirectUri' => $this->redirectUri,
            'urlAuthorize' => 'https://your-authorization-url.com', // Authorization endpoint URL
            'urlAccessToken' => 'https://your-token-url.com', // Token endpoint URL
            'urlResourceOwnerDetails' => 'https://your-user-info-url.com', // User info endpoint URL
            'scopes' => $this->scopes
        ]);
    }

    public function getAuthorizationUrl()
    {
        $authorizationUrl = $this->provider->getAuthorizationUrl(['scope' => $this->scopes]);
        return $authorizationUrl;
    }

    public function authenticate($code)
    {
        $accessToken = $this->provider->getAccessToken('authorization_code', [
            'code' => $code
        ]);

        $resourceOwner = $this->provider->getResourceOwner($accessToken);

        return [
            'access_token' => $accessToken->getToken(),
            'expires' => $accessToken->getExpires(),
            'refresh_token' => $accessToken->getRefreshToken(),
            'resource_owner' => $resourceOwner->toArray()
        ];
    }
}
				
			

Next, open the routes/web.php file and add the following routes:

				
					<?php

use Illuminate\Support\Facades\Route;
use App\AuthProvider;

$authProvider = new AuthProvider();

Route::get('/login', function () use ($authProvider) {
    $authorizationUrl = $authProvider->getAuthorizationUrl();
    return Redirect::away($authorizationUrl);
});

Route::get('/callback', function () use ($authProvider) {
    $code = request()->get('code');
    $authData = $authProvider->authenticate($code);

    // Access the authentication data
    $accessToken = $authData['access_token'];
    $expires = $authData['expires'];
    $refreshToken = $authData['refresh_token'];
    $resourceOwner = $authData['resource_owner'];

    // Use the authentication data as needed
    dd($accessToken, $expires, $refreshToken, $resourceOwner);
});
				
			

Make sure to replace 'your-client-id', 'your-client-secret', 'https://your-authorization-url.com', 'https://your-token-url.com', and 'https://your-user-info-url.com' with the appropriate values for your specific identity provider and client.

Now, you can navigate to /login in your browser to initiate the authentication flow. After authentication, you will be redirected to /callback, where you can access the authentication data.

Please note that this is a basic example, and in a real-world Laravel application, you would typically store the authentication data in the session, implement error handling, and customize the logic based on your specific requirements. Additionally, you may need to configure additional options and implement additional logic depending on your use case.