N/https Module Script Samples

The following script samples demonstrate how to use the features of the N/https module:

Generate a Secure Token and a Secret Key

Important:

This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.

The following sample shows how to use a GUID to generate a secure token and a secret key. To run this sample in the debugger, you must replace the GUID with one specific to your account.

Note:

This sample script uses the require function so that you can copy it into the SuiteScript Debugger and test it. You must use the define function in an entry point script (the script you attach to a script record and deploy). For more information, see SuiteScript 2.x Script Basics and SuiteScript 2.x Script Types.

Important:

This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.

            /**
 * @NApiVersion 2.1
 */

// This script uses a GUID to generate a secure token and a secret key.
require(['N/https', 'N/runtime'], (https, runtime) => {
    function createSecureString() {
        const passwordGuid = '{284CFB2D225B1D76FB94D150207E49DF}';
        let secureToken = https.createSecureString({
            input: passwordGuid
        });
        let secretKey = https.createSecretKey({
            input: passwordGuid
        });
        secureToken = secureToken.hmac({
            algorithm: https.HashAlg.SHA256,
            key: secretKey
        });
    }
    createSecureString();
}); 

          

Create a Form with a Field that Generates a GUID

Important:

This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.

The following sample shows how to use a Suitelet to create a form field that generates a GUID. For more information about credential fields, see Form.addCredentialField(options).

Note:

This script sample uses the define function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.

Note:

The default maximum length for a credential field is 32 characters. If needed, use the Field.maxLength property to change this value.

The values for restrictToDomains, restrictToScriptIds, and baseUrl in this sample are placeholders. You must replace them with valid values from your NetSuite account.

Important:

This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.

            /**
 * @NApiVersion 2.1
 * @NScriptType Suitelet
 */

// This script creates a form with a credential field.
define(['N/ui/serverWidget', 'N/https', 'N/url'], (serverWidget, https, url) => {
    function onRequest(context) {
        if (context.request.method === 'GET') {
            const form = serverWidget.createForm({
             title: 'Password Form'
            });

            const credField = form.addCredentialField({
                id: 'password',
                label: 'Password',
                restrictToDomains: ['<accountID>.app.netsuite.com'],
                restrictToCurrentUser: false,
                restrictToScriptIds: 'customscript_my_script'
            });

            credField.maxLength = 32;

            form.addSubmitButton();

            context.response.writePage({
                pageObject: form
                });
        } 
        else {
            // Request to an existing Suitelet with credentials
            let passwordGuid = context.request.parameters.password;

            // Replace SCRIPTID and DEPLOYMENTID with the internal ID of the suitelet script and deployment in your account 
            let baseUrl = url.resolveScript({
                scriptId: SCRIPTID,
                deploymentId: DEPLOYMENTID,
                returnExternalURL: true
            });

            let authUrl = baseUrl + '&pwd={' + passwordGuid + '}';

            let secureStringUrl = https.createSecureString({
                input: authUrl
            });

            let headers = ({
               'pwd': passwordGuid
            });

            let response = https.post({
                credentials: [passwordGuid],
                url: secureStringUrl,
                body: {authorization:' '+ passwordGuid + '', data:'anything can be here'},
                headers: headers
            });
        }
    }
    return {
        onRequest: onRequest
    };
}); 

          

Create an Authentication Header Using a Secure String

Important:

This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.

The following sample shows how to use a Suitelet to create an authentication header and send the request to a service (which requires an authentication header) using an https.SecureString. For more information about SecureString, see https.SecureString.

Note:

This script sample uses the define function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.

Important:

This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.

            /**
 * @NApiVersion 2.1
 * @NScriptType Suitelet
 */
 
// This script creates an authentication header using an https.SecureString.
define(['N/https', 'N/encode'], (https, encode) => {
    function onRequest(context) {

        // Secrets with these two Script IDs must be existing and allowed for this script
        const nameToken = "custsecret_myName";
        const passwordToken = "custsecret_mypPassword";

        // Create BASE-64 encoded name:password pair
        const secStringKeyInBase64 = https.createSecureString({
            input: "{" + nameToken + "}:{" + passwordToken + "}"
        });

        secStringKeyInBase64.convertEncoding({
            toEncoding: encode.Encoding.BASE_64,
            fromEncoding: encode.Encoding.UTF_8
        });

        // Construct the Authorization header
        const secStringBasicAuthHeader = https.createSecureString({
            input: "Basic "
        });

        secStringBasicAuthHeader.appendSecureString({
            secureString: secStringKeyInBase64,
            keepEncoding: true
        });

        // Send the request to third party with the Authorization header
        const resp = https.get({
            url: "myUrl",
            headers: {
                "Authorization": secStringBasicAuthHeader
            }
        });
    };
    return {
        onRequest: onRequest
    };
}); 

          

Concatenate API Secrets with Strings

Important:

This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.

The following sample shows how to concatenate a string value to use as an API secret. API Secrets are string values that cannot be concatenated directly. In some cases, a code-generated string (for example, date stamp, account ID, sequence numbers) needs to be merged with the API secret. To merge the values, the N/https module must be imported on the script file and use the createSecureString() API to initialize both secret API values and ordinary string.

Note:

This sample script uses the require function so that you can copy it into the SuiteScript Debugger and test it. You must use the define function in an entry point script (the script you attach to a script record and deploy). For more information, see SuiteScript 2.x Script Basics and SuiteScript 2.x Script Types.

Important:

This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.

            /**
 * @NApiVersion 2.1
 */

// This script uses appendSecureString to concatenate strings to use as an API secret.
require(['N/https', 'N/runtime'], (https, runtime) => {
    function concatToCreateSecureString() {
        let baseUrl = https.createSecureString({
            input: 'www.someurl.com/add?apikey='
         });
        let apiKey = https.createSecureString({
            input: '{CUSTSECRET_SOME_INTEGRATION}'
        });
        let url = baseUrl.appendSecureString({
            secureString: apiKey
        });
    }
    concatToCreateSecureString();
}); 

          

Create a JWT Token Using a SecureString

Important:

This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.

The following sample shows how to use a JWT token using https.SecureString. For more information about SecureString, see https.SecureString.

Note:

This script sample uses the define function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.

Important:

This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.

            /**
 * @NApiVersion 2.1
 * @NScriptType Suitelet
 */

// This script creates a JWT token using https.SecureString.
define(['N/https', 'N/encode'], (https, encode) => {
    function onRequest(context) {
        let nameToken = "custsecret_myName";
        let passwordToken = "custsecret_myPassword";
        let headerObj = {
            "alg": "HS256",
            "typ": "JWT"
        }
        let payloadObj = {
            "sub": "1234567890",
            "name": "John Doe",
            "iat": 1516239002
        }

        let headerJSON = JSON.stringify(headerObj);
        let payloadJSON = JSON.stringify(payloadObj);
        let headerBASE64 = encode.convert({
            string: headerJSON,
            inputEncoding: encode.Encoding.UTF_8,
            outputEncoding: encode.Encoding.BASE_64_URL_SAFE
        });

        let payloadBASE64 = encode.convert({
            string: payloadJSON,
            inputEncoding: encode.Encoding.UTF_8,
            outputEncoding: encode.Encoding.BASE_64_URL_SAFE
        });

        headerBASE64 = headerBASE64.replace(/=/g, ""); // remove = padding as per JWT spec 'base64UrlEncode' - URL-safe BASE-64 without padding
        payloadBASE64 = payloadBASE64.replace(/=/g, ""); // remove = padding as per JWT spec 'base64UrlEncode' - URL-safe BASE-64 without padding
        
        let secStringJwtSignature = https .createSecureString({
            input: headerBASE64 + "." + payloadBASE64
        })
        .hmac({
            algorithm: https.HashAlg.SHA256,
            key: https.createSecretKey({
                     secret: passwordToken,
                     encoding: encode.Encoding.UTF_8
            }),
           resultEncoding: encode.Encoding.BASE_64_URL_SAFE
        })
        .replaceString({ // remove = padding as per JWT spec 'base64UrlEncode' - URL-safe BASE-64 without padding
             pattern: "=", 
             replacement: ""
        })

        let secStringJwtAuthHeader = https .createSecureString({
            input: "Bearer " + headerBASE64 + "." + payloadBASE64 + "."
        })
        .appendSecureString({
            secureString: secStringJwtSignature,
            keepEncoding: true
        })

        // Reflect the response using a echo-request suitelet
        let resp = https.get({
            url: "myURL",
            headers: {
                "Authorization": secStringJwtAuthHeader
            } 
        });

        { 
            log.debug("resp-code", resp.code);
            log.debug("resp-body", resp.body);

            let respAuth = JSON.parse(resp.body)["headers"]["Authorization"];

            log.debug("reps-head-auth", respAuth);
            log.debug("reps-head-auth-expected", 
                "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.uel3RLILSJ9Q9W2Gomh8vAJQAgdbnd6TS4b7plyFOtA" ); // see https://jwt.io/#debugger-io
        } 
    }
    return {
        onRequest: onRequest
    };
}); 

          

General Notices