PHP code example of bde42 / oauth2-marvin

1. Go to this page and download the library: Download bde42/oauth2-marvin library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bde42 / oauth2-marvin example snippets


if (session('current_user') == null)
{
    $provider = new \BDE42\OAuth2\Client\Provider\Marvin([
        'clientId'          => 'your_client_id',
        'clientSecret'      => 'your_secret',
        'redirectUri'       => 'https://uri/to/redirect'
    ]);
    
    // If we don't have an authorization code then get one
    if (!isset($_GET['code'])) {
        $authUrl = $provider->getAuthorizationUrl(/*options*/);
        session(['oauth2state' => $provider->getState()]);
        return redirect($authUrl);

    // Check given state against previously stored one to mitigate CSRF attack
    } else if (empty($_GET['state']) || $_GET['state'] !== session('oauth2state'))
    {
        session(['oauth2state' => null]);
        exit('Invalid state');
    }
    
    // Try to get an access token (using the authorization code grant)
    $token = $provider->getAccessToken('authorization_code', [
        'code' => $_GET['code']
    ]);
    
    // Try to get an access token (using the authorization code grant)
    try {
        $user = $provider->getResourceOwner($token);
    } catch (Exception $e) {
        exit('Oh dear...');
    }

    session(['current_user' => $user->getUserInfos()]); //Basic informations (uid, email, name and login)
    //$user->toArray() //Get all user informations whose you have the access authorization
    
    print_r ("NEW USER : ".json_encode(session('current_user')));
} else {
    print_r ("REGISTERED USER : ".json_encode(session('current_user')));
}