wonder95's avatar

Authenticating to Service via OAuth

I need to connect my Laravel app to a service called Brivo (for adding/updating credentials for a gate system) via their API which uses OAuth2, and I'm having issues figuring how to get started. I did it with Slack a few years ago, but they provide tools like an embeddable button that Brivo doesn't. I found this provider, but I can't figure out how to get started from within my app. For instance, where do I put the code in the README to pass my client ID and secret and get the token? Is that something like an artisan command that I run, and then stash the token and pass it for every call to Brivo?

Any pointers to good tutorials or starting out instructions would be helpful.

Thanks.

0 likes
4 replies
chiefguru's avatar

Hi @wonder95 I don' know if this will be helpful to you, we have to get an OAuth token from zoom in order to push data to webinars and this is how we do it.

    private function buildApiToken()
    {
        $zoomOauthEndpoint = 'https://zoom.us/oauth/token';
        $accountID = config('webinar.zoom.account');
        $clientID = config('webinar.zoom.client');
        $secret = config('webinar.zoom.secret');

        $response = Http::asForm()
            ->withBasicAuth($clientID, $secret)
            ->withHeaders([
                'Host' => 'zoom.us',
            ])
            ->post($zoomOauthEndpoint, [
                'grant_type' => 'account_credentials',
                'account_id' => $accountID,
            ]);
        return $response->object()->access_token;
    }
martinbean's avatar

Is that something like an artisan command that I run, and then stash the token and pass it for every call to Brivo?

@wonder95 No. It’s OAuth. So you need to redirect to https://auth.brivo.com/oauth/authorize with the parameters the docs tells you to pass. The user will be prompted to authorise your app to access their Brivo account. If they authorise the request, Brivo will then redirect back to your app with a code, that you can then perform a HTTP request to https://auth.brivo.com/oauth/token to “swap” for an actual OAuth access token. You would associate this access token with a user in your application, and use that access token in any subsequent requests to Brivo’s API.

wonder95's avatar

OK, I think I get it. More questions:

  • From an app perspective, do I need some sort of 'Authorize button that redirects to that /oauth/authorize url, which then calls my callback_uri, and from there I stash the token and use it in subsequent calls?

  • I found this library , which wraps the PHPLeague oauth2-client to help with it. Would it just be a matter of extending it to get the token, and then wrapping it in a service provider and calling it in my authentication controller?

I'm just trying to figure out how to kick off the authentication process.

LaryAI's avatar
Level 58

To integrate OAuth2 for Brivo in your Laravel application, you can follow these steps using the oauth2-brivo package you found. This will involve setting up the OAuth client, obtaining tokens, and using these tokens to make authenticated requests to the Brivo API.

Step 1: Install the OAuth2 Brivo Provider

First, you need to install the oauth2-brivo package via Composer. Run this command in your Laravel project directory:

composer require drewhammond/oauth2-brivo

Step 2: Configuration

After installing the package, you need to configure your OAuth credentials. You can store these in your .env file for security and ease of access:

BRIVO_CLIENT_ID=your-client-id
BRIVO_CLIENT_SECRET=your-client-secret
BRIVO_REDIRECT_URI=http://your-redirect-uri

Step 3: Set Up the OAuth Client

You can create a service class in Laravel to encapsulate the OAuth logic. For example, create a file named BrivoService.php in app/Services:

<?php

namespace App\Services;

use League\OAuth2\Client\Provider\GenericProvider;

class BrivoService
{
    protected $provider;

    public function __construct()
    {
        $this->provider = new GenericProvider([
            'clientId'                => env('BRIVO_CLIENT_ID'),
            'clientSecret'            => env('BRIVO_CLIENT_SECRET'),
            'redirectUri'             => env('BRIVO_REDIRECT_URI'),
            'urlAuthorize'            => 'https://auth.brivo.com/oauth/authorize',
            'urlAccessToken'          => 'https://auth.brivo.com/oauth/token',
            'urlResourceOwnerDetails' => 'https://auth.brivo.com/api/userinfo'
        ]);
    }

    public function getAuthorizationUrl()
    {
        return $this->provider->getAuthorizationUrl();
    }

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

Step 4: Handling Redirects and Tokens

In your web routes (routes/web.php), set up routes to handle the OAuth redirect and callback:

use App\Http\Controllers\Auth\BrivoController;

Route::get('/auth/brivo', [BrivoController::class, 'redirect'])->name('brivo.redirect');
Route::get('/auth/brivo/callback', [BrivoController::class, 'callback'])->name('brivo.callback');

Create a controller BrivoController.php in app/Http/Controllers/Auth:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Services\BrivoService;
use Illuminate\Http\Request;

class BrivoController extends Controller
{
    public function redirect(BrivoService $brivo)
    {
        return redirect()->away($brivo->getAuthorizationUrl());
    }

    public function callback(Request $request, BrivoService $brivo)
    {
        $accessToken = $brivo->getAccessToken($request->code);
        // Store this access token securely and use it for subsequent API requests to Brivo
    }
}

Step 5: Making API Requests

With the access token, you can now make authenticated requests to the Brivo API. Ensure you securely store and reuse the token, and handle token refresh scenarios as needed.

Conclusion

This setup should help you authenticate and interact with the Brivo API via OAuth2 in your Laravel application. For more detailed handling, such as token storage and refresh, consider implementing additional methods in the BrivoService class.

Please or to participate in this conversation.