How to implement OAuth authentication in a Node.js application using the BoldSign API?

OAuth2 is a protocol that lets applications securely access the BoldSign API. It uses the OpenID Connect framework for strong and standardized authentication.

Below is a detailed walkthrough with code examples for each part of the process.

Create an OAuth2 Application in BoldSign

To start the OAuth2 authorization process, you need to create an OAuth2 application in BoldSign. This application will provide you with the necessary credentials client ID and client secret to authenticate and interact with the BoldSign API.

To create an OAuth app, refer to the article Create an OAuth app

Implement Authorization Code Flow

To begin the OAuth2 authorization code flow with Node.js, you first need to set up an Express server. This server will handle the redirect URI endpoint, which is crucial for receiving the authorization code and exchanging it for access and refresh tokens. Here's a step-by-step guide to help you get started.

Code snippet

const express = require('express'); 
const axios = require('axios'); 
const app = express(); const port = 3000; // Replace with your actual values 
const CLIENT_ID = 'YOUR_CLIENT_ID'; // Replace it with your client id from BoldSign application 
const CLIENT_SECRET = 'YOUR_CLIENT_SECRET'; // Replace it with your client secret from BoldSign application 
const REDIRECT_URI = 'http://localhost:3000/callback'; 
const AUTHORIZATION_URL = 'https://account.boldsign.com/connect/authorize'; 
const TOKEN_URL = 'https://account.boldsign.com/connect/token'; 
const SCOPE = 'openid profile email offline_access BoldSign.Documents.All';
const CODE_VERIFIER = 'YOUR_CODE_VERIFIER';
const CODE_CHALLENGE = 'YOUR_CODE_CHALLENGE';

app.get('/authorize', (req, res) => {
    const authorizationUri = `${AUTHORIZATION_URL}?response_type=code&client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&scope=${SCOPE}&code_challenge=${CODE_CHALLENGE}&code_challenge_method=S256`; res.redirect(authorizationUri); });
 app.get('/callback', async (req, res) => { 
    const authCode = req.query.code; 
    try { 
        const tokenResponse = await axios.post( 
            TOKEN_URL, 
            new URLSearchParams({ 
                grant_type: 'authorization_code', 
                client_id: CLIENT_ID, 
                client_secret: CLIENT_SECRET,
                 code: authCode,
                  redirect_uri: REDIRECT_URI,
                   code_verifier: CODE_VERIFIER
                    })
                     ); 
                     const { access_token, refresh_token } = tokenResponse.data; 
                     res.json({ access_token, refresh_token }); 
                     } catch (error) { 
                        res.status(500).send('Error exchanging code for access token');
                         } 
                         });
 app.listen(port, () => { 
    console.log(`Server running at http://localhost:${port}`);
     });
     

In the provided code example, replace port with your actual values, CLIENT ID with your client id from BoldSign application, CLIENT SECRET with your client secret from BoldSign application.

Generate PKCE Code Verifier and Challenge

When implementing OAuth2 with PKCE (Proof Key for Code Exchange), you need to generate a code verifier and a code challenge to enhance the security of your authorization flow. The code verifier is a random string, and the code challenge is a hashed version of the verifier, both of which are used to verify the authenticity of the authorization request.

To generate a PKCE code verifier and challenge in Node.js, you can use the following utility function:

Code snippet

const crypto = require('crypto'); 
function base64URLEncode(str) { 
    return str.toString('base64') 
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
     .replace(/=/g, ''); 
     } 
function sha256(buffer) { 
    return crypto.createHash('sha256').update(buffer).digest(); 
    } 
function generatePKCECodes() { 
    const codeVerifier = base64URLEncode(crypto.randomBytes(32)); 
    const codeChallenge = base64URLEncode(sha256(codeVerifier));
     return { codeVerifier, codeChallenge }; 
     } 
const { codeVerifier, codeChallenge } = generatePKCECodes(); 
console.log('Code Verifier:', codeVerifier); 
console.log('Code Challenge:', codeChallenge);
module.exports = { generatePKCECodes };     

Refresh Access Token

Once you have the refresh token, you can use it to obtain a new access token without requiring the user to reauthorize your application. This process ensures continuous access to the BoldSign API. Here's how you can do it:

Code snippet

async function refreshAccessToken(refreshToken) { 
    try { 
        const response = await axios.post( 
            'https://account.boldsign.com/connect/token', 
            new URLSearchParams({ 
                'grant_type': 'refresh_token', 
                'client_id': CLIENT_ID, 
                'client_secret': CLIENT_SECRET, 
                'refresh_token': refreshToken 
                })
                 ); 
                 const { access_token, refresh_token } = response.data;
                 console.log('New access token:', access_token); 
                 console.log('New refresh token:', refresh_token); 
                 } catch (error) { 
                    console.error('Error refreshing access token', error); 
                    }
                     } 
                     // Call the function with the current refresh token 
                     refreshAccessToken('YOUR_CURRENT_REFRESH_TOKEN');
     

Testing the Token Refresh Endpoint

You can test the /refresh-token endpoint using Postman or an HTML form. Here’s how to do it with Postman:

  1. Open Postman and create a new POST request.

  2. Set the URL to {Your application URL}/refresh-token.

  3. Set the Body to x-www-form-urlencoded and add the following key-value pairs:

  4. refresh_token: The refresh token you received from the initial token exchange.

  5. Send the Request and you should receive a new access token and refresh token in the response.

Using these techniques, you can securely integrate OAuth2 authentication into your Node.js applications and access the BoldSign API.