Skip to content

webiik/oauth2-client

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 

Repository files navigation

OAuth2Client

The OAuth2Client allows you to connect to any OAuth2 server. Just follow the procedure described in the example below.

Installation

composer require webiik/oauth2client

Example

// Facebook Example

// Prepare dependencies
$chc = new \Webiik\CurlHttpClient\CurlHttpClient();

// Instantiate OAuth2 client
$oAuth2Client = new \Webiik\OAuth2Client\OAuth2Client($chc);

// Your callback URL after authorization
// OAuth2 server redirects users to this URL, after user verification
$oAuth2Client->setRedirectUri('https://127.0.0.1/webiik/');

// API endpoints
$oAuth2Client->setAuthorizeUrl('https://www.facebook.com/v3.3/dialog/oauth');
$oAuth2Client->setAccessTokenUrl('https://graph.facebook.com/v3.3/oauth/access_token');
$oAuth2Client->setValidateTokenUrl('https://graph.facebook.com/debug_token');

// API credentials (create yours at https://developers.facebook.com/apps/)
$oAuth2Client->setClientId('your-client-id');
$oAuth2Client->setClientSecret('your-client-sectret');

// Make API calls...

// Define scope
$scope = [
    'email',
];

if (!isset($_GET['code'])) {
    // 1. Prepare Facebook user login link with specified scope and grand type
    echo '<a href="' . $oAuth2Client->getAuthorizeUrl($scope) . '" target="_blank">Authorize with Facebook</a><br/>';
}

if (isset($_GET['code'])) {
    // 2. Verify code to obtain user access_token
    $user = $oAuth2Client->getAccessTokenByCode();

    // 3. Verify clientId and clientSecret to obtain app access_token
    $app = $oAuth2Client->getAccessTokenByCredentials();
}

if (isset($user, $user['access_token']) && isset($app, $app['access_token'])) {
    // 4. User and app access_tokens are valid, user and app are authorized by Facebook
    // Access protected resources...
    
    // Get user id
    $tokenInfo = $oAuth2Client->getTokenInfo($user['access_token'], $app['access_token'], true);
    if (!isset($tokenInfo['data'], $tokenInfo['data']['user_id'])) {
        // Err: Can't obtain user id 
        print_r($tokenInfo);
        exit;
    }
    
    // Get additional user info
    $fields = [
        'name',
        'first_name',
        'middle_name',
        'last_name',
        'email',
    ];
    $reg = $chc->prepareRequest('https://graph.facebook.com/v3.3/' . $tokenInfo['data']['user_id'] . '/?access_token=' . $user['access_token'] . '&fields=' . implode(',', $fields));
    $res = $chc->send($reg);
    if ($res->isOk()) {
        header('Content-Type: application/json');
        echo $res->body();
    }    
}

Configuration

Before you can connect to any OAuth2 server, you have to properly configure access credentials and endpoints.

setClientId

setClientId(string $id): void

setClientId() sets client id.

$oAuth2Client->setClientId('your-client-id');

setClientSecret

setClientSecret(string $secret): void

setClientSecret() sets client secret.

$oAuth2Client->setClientSecret('your-client-sectret');

setRedirectUri

setRedirectUri(string $url): void

setRedirectUri() sets redirect URI to redirect a user after authorization by OAuth2 server.

$oAuth2Client->setRedirectUri('https://127.0.0.1/webiik/');

setAuthorizeUrl

setAuthorizeUrl(string $url): void

setAuthorizeUrl() sets URL to authorize a user by OAuth2 server.

$oAuth2Client->setAuthorizeUrl('https://www.facebook.com/v3.2/dialog/oauth');

setAccessTokenUrl

setAccessTokenUrl(string $url): void

setAccessTokenUrl() sets URL to obtain a access token.

$oAuth2Client->setAccessTokenUrl('https://graph.facebook.com/v3.2/oauth/access_token');

setValidateTokenUrl

setValidateTokenUrl(string $url): void

setValidateTokenUrl() sets URL to validate a access token. This endpoint is not official part of OAuth2 specifications, however Google, Facebook etc. provide it.

$oAuth2Client->setValidateTokenUrl('https://graph.facebook.com/debug_token');

Login

getAuthorizeUrl

getAuthorizeUrl(array $scope = [], string $responseType = 'code', string $state = ''): string

getAuthorizeUrl() prepares a correct link to a URL set by setAuthorizeUrl().

Parameters

  • scope defines access scope of your app. Learn access scopes of individual OAuth2 servers.
  • responseType possible response types are code, token, id_token...
  • state read about state parameter.
$link = $oAuth2Client->getAuthorizeUrl(['email'])

Authorization

OAuth2Client allows you to get access token by all grant types provided by OAuth2 protocol. Read more about grant types.

getAccessTokenByCode

getAccessTokenByCode()

getAccessTokenByCode() makes HTTP POST request to a URL set by setAccessTokenUrl(). Returns an array with token(s) on success and a string with cURL error message on error. This grant type is usually used by apps for authenticating users.

$user = $oAuth2Client->getAccessTokenByCode();

getAccessTokenByPassword

getAccessTokenByPassword(string $username, string $password, array $scope = [])

getAccessTokenByPassword() makes HTTP POST request to a URL set by setAccessTokenUrl(). Returns an array with token(s) on success and a string with cURL error message on error. This grant type is usually used by trusted apps for authenticating users.

$user = $oAuth2Client->getAccessTokenByCode();

getAccessTokenByCredentials

getAccessTokenByCredentials()

getAccessTokenByCredentials() makes HTTP POST request to a URL set by setAccessTokenUrl(). Returns an array with token(s) on success and a string with cURL error message on error. This grant type is usually used for server-to-server communication.

$app = $oAuth2Client->getAccessTokenByCredentials();

getAccessTokenByRefreshToken

getAccessTokenByRefreshToken(string $refreshToken)

getAccessTokenByRefreshToken() makes HTTP POST request to a URL set by setAccessTokenUrl(). Returns an array with token(s) on success and a string with cURL error message on error. Usually you can get $refreshToken by setting scope offline_access when calling getAuthorizeUrl(). Read more about refresh_token. It's used to obtain a renewed access token.

$token = $oAuth2Client->getAccessTokenByRefreshToken($refreshToken);

getAccessTokenBy

getAccessTokenBy(array $params)

getAccessTokenBy() makes HTTP POST request to a URL set by setAccessTokenUrl(). Returns an array with token(s) on success and a string with cURL error message on error. This method allows you to get access token by custom parameters.

// Get access token by code
$user = $oAuth2Client->getAccessTokenBy([
    'redirect_uri' => 'https://127.0.0.1/webiik/',
    'grant_type' => 'authorization_code',
    'code' => $_GET['code'],
]);

getTokenInfo

getTokenInfo(string $inputToken, string $accessToken, bool $useGet = false)

getTokenInfo() makes HTTP POST request to a URL set by setValidateTokenUrl(). Returns an array with token(s) on success and a string with cURL error message on error. This is not official part of OAuth2 specifications, however Google, Facebook etc. provide it.

$token = $oAuth2Client->getTokenInfo($inputToken, $accessToken);

Resources

About

[READ ONLY - subtree split] The OAuth2Client allows you to connect to any OAuth2 server.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages