March 20, 2018 | Anil Kumar

Implement OAuth 2.0 / OpenID Connect using a sample application in just a few minutes

This article demonstrates how to implement the OAuth 2.0 and OpenID Connect workflows in just a few minutes.

Yes, that’s right, you can master the authorization workflows in just under 15 minutes. It provides you with a clear understanding of:

  • Implementing OAuth 2.0 in your app
  • Making API calls using the tokens
  • How to refresh the tokens
  • The difference between OpenID Connect and OAuth 2.0 authorization workflows

For starters, refer to our earlier posted blog introducing the release of OAuth 2.0 and OpenID Connect: https://developer.intuit.com/hub/blog/2017/07/17/oauth-2-0openid-connect-now-available-new-developers

Note: This blog showcases the OAuth 2.0 and OpenID Connect authorization flows in JavaScript and PHP languages, only.

Implement OAuth 2.0 in your App

Overall, just two HTTP requests are necessary:

  • The first requests an authorization code.
  • The second exchanges the authorization code for an access token.

On a high level, here is what’s needed to implement OAuth2.0 in your application:

1. Based on the redirect URI in your applications Keys tab on https://developer.intuit.com/, the authorization URL is created (this is supported in the demo code).

2. Request #1 launches a browser window to open the authorization URL.

3. This URL redirects back to the pre-configured redirect URI (callback). Code at this location extracts the code and

4. Request #2 exchanges the code for an access_token.

5. The browser window closes.

Get Started with the Sample:

To get started, perform the following steps:

1. Clone the Github Repository. Refer to the instructions in README.md included in the corresponding demo:

2. Create an App, if you have not created by logging into Developer Portal

3. Get the Client ID and Client Secret keys from your app’s Keys tab.

4.  Enter this redirect URI in your app’s Keys tab ( this is for sandbox ONLY ) : http://localhost:3000/callback

5.  Add your keys to the Sample app’s configuration file:

Note: If you are implementing TLS/SSL support in your app, you need to expose it over the internet. Refer to the appropriate README.md for more information: ( Javascript, PHP )

6. Start the demo app:

Make an API call using the generated tokens

Now, make an API call using the tokens generated from the previous section.

Javascript

We use the Node-QuickBooks-SDK to make the API call, as follows:

  • Create a QuickBooks object and pass the parameters (clientID, clientSecret, access_token, refresh_token, realmID, and so on). See here if you have any doubts.
  • Issue an API call to retrieve the CompanyInfo object from the QuickBooks company: See here

 

app.get('/getCompanyInfo', function(req,res){

    // save the access token somewhere on behalf of the logged in user
    var qbo = new QuickBooks(config.clientId,
        config.clientSecret,
        accessToken.access_token,
        false, 
        realmId,
        config.useSandbox,
        true, 
        4, 
        '2.0',
        accessToken.refresh_token);

    qbo.getCompanyInfo(realmId, function(err, companyInfo) {
        if (err) {
            console.log(err);
            res.send(err);
        }
        else {
            console.log("The response is :" + JSON.stringify(companyInfo,null,2));
            res.send(companyInfo);
        }
    });
});


PHP

We use the QuickBooks-V3-PHP-SDK to make the API call, as follows:

  • Create the DataService object by passing the parameters (clientID, clientSecret, redirectUri, scope, and baseUrl is ). See here if you have any doubts.
  • Make an API to retrieve the CompanyInfo object from the QuickBooks company: See here
function makeAPICall()
{

    // Create SDK instance
    $config = include('config.php');
    $dataService = DataService::Configure(array(
        'auth_mode' => 'oauth2',
        'ClientID' => $config['client_id'],
        'ClientSecret' =>  $config['client_secret'],
        'RedirectURI' => $config['oauth_redirect_uri'],
        'scope' => $config['oauth_scope'],
        'baseUrl' => "development"
    ));

    /*
     * Retrieve the accessToken value from session variable
     */
    $accessToken = $_SESSION['sessionAccessToken'];

    /*
     * Update the OAuth2Token of the dataService object
     */
    $dataService->updateOAuth2Token($accessToken);
    $companyInfo = $dataService->getCompanyInfo();

    print_r($companyInfo);
    return $companyInfo;
}

How to Refresh the tokens

Access token lifetime and how to refresh the access token

Access tokens are valid for 3600 seconds (one hour), after which time you need to get a fresh token using the latest refresh_token returned to you from the previous request.

To learn more about refreshing the access token, see the following documentation page: https://developer.intuit.com/docs/00_quickbooks_online/2_build/00_build#/Refreshing_the_access_token

Here’s how we do it in the sample code:

Javascript

  • Create a QuickBooks object and pass the parameters (clientID, clientSecret, access_token, refresh_token, realmID, and so on).
  • Call the refreshAccessToken() method of the qbo object.
app.get('/refreshAccessToken', function(req,res){

    // save the access token somewhere on behalf of the logged in user
    var qbo = new QuickBooks(config.clientId,
        config.clientSecret,
        accessToken.access_token,
        false, 
        realmId,
        config.useSandbox,
        true,
        4,
        '2.0',
        accessToken.refresh_token);

    qbo.refreshAccessToken(function(err, refreshToken) {
        if (err) {
            console.log(err);
            res.send(err);
        }
        else {
            console.log("The response refresh is :" + JSON.stringify(refreshToken,null,2));
            res.send(refreshToken);
        }
});


PHP

  • Create the DataService object by passing the parameters (clientID, clientSecret, redirectUri, scope, and baseUrl is ).
  • Invoke the getOAuth2LoginHelper() method from the DataService object created above.
  • Call the refreshToken() method of the OAuth2LoginHelper object.
function refreshToken()
{

    // Create SDK instance
    $config = include('config.php');
     /*
     * Retrieve the accessToken value from session variable
     */
    $accessToken = $_SESSION['sessionAccessToken'];
    $dataService = DataService::Configure(array(
        'auth_mode' => 'oauth2',
        'ClientID' => $config['client_id'],
        'ClientSecret' =>  $config['client_secret'],
        'RedirectURI' => $config['oauth_redirect_uri'],
        'baseUrl' => "development",
        'refreshTokenKey' => $accessToken->getRefreshToken(),
        'QBORealmID' => "The Company ID which the app wants to access",
    ));

    /*
     * Update the OAuth2Token of the dataService object
     */
    $OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
    $refreshedAccessTokenObj = $OAuth2LoginHelper->refreshToken();
    $dataService->updateOAuth2Token($refreshedAccessTokenObj);

    $_SESSION['sessionAccessToken'] = $refreshedAccessTokenObj;

    print_r($refreshedAccessTokenObj);
    return $refreshedAccessTokenObj;
}

The difference between OpenID Connect and OAuth 2.0

OpenID Connect is a simple identity layer on top of the OAuth 2.0 protocol. It allows clients to verify the identity of the end user based on the authentication performed by an authorization server, as well as to obtain basic profile information about the end user in an interoperable and REST-like manner.

 

This demo app showcases both OAuth 2.0 and OpenID Connect authorization workflows.

OAuth 2.0

  • Scope: space-delimited set of permissions that the application requests
    • com.intuit.quickbooks.accounting — QuickBooks Online API
    • com.intuit.quickbooks.payment — QuickBooks Payments API

OAuth 2.0 authorization flow:

OpenID Connect

  • Scope: space-delimited set of permissions that the application requests
    • openid—QuickBooks Online API
    • profile—QuickBooks Payments API
    • email—user’s email address
    • phone—user’s phone number
    • address—user’s physical address

OpenID Connect authorization flow:

  • For OpenID Connect documentation, click here.

Learn more

  • For more details on OAuth 2.0, such as generating a new access token using a refresh token, refer here.
  • To call the APIs programmatically, leverage the official SDKs which take care of authentication, data serialization, and several other aspects of QuickBooks Online REST API calls.
  • Links to sample programs that use the official SDKs for some basic use cases are found here.

If you have any questions regarding this, please reach out to us online in our community or open a support case: https://help.developer.intuit.com/s/

Comments

View all
Load more comments