REST API supports only ‘Basic authentication’ and ‘OAuth 1.0a’ authentication methods.
We can generate Basic authentication headers for REST API requests in suitescript using suitescript modules from the username and API token(password).
Authentication header need to be passed as header with every request that require authentication. If we use Postman software we can see an authentication header generated when authentication type is selected and necessary values are provided. But during NetSuite-REST API integration, it is more practical to create a function for generating authentication header whenever username and password is provided rather than hardcoding it.
Steps to generate authentication header:
1.Build a string of the form username:password
2.Encode the string to Base64
3.Supply an authorization header with format Authorization: Basic {encoded-string}. Make sure to replace {encoded-string} with your encoded string from Step 2.
For example, if your username is ‘admin‘ and password is ‘NS1234pw‘ then the string is ‘admin:NS1234pw‘. On encoding to base64 we will get: ‘YWRtaW46TlMxMjM0cHc=‘.
After adding the authentication type as prefix, the header will be ‘Basic YWRtaW46TlMxMjM0cHc=‘.
Authentication header using Suitescript
We can use the suitescript module: ‘N/encode’ for converting a string(UTF-8) to Base64 type.
Refer the following function for the suitescript implementaion of above above discussed steps:
define(['N/encode'],
(encode) => {
...
...
...
function authHeaderRestAPI(username, password){
try{
let str = username+":"+password;
let encodedStr = encode.convert({
string: str,
inputEncoding: encode.Encoding.UTF_8,
outputEncoding: encode.Encoding.BASE_64
});
encodedStr = "Basic "+encodedStr;//REST API uses "username:password" converted to Base64 format and attached to "Basic " as authentication header for basic authentication
//log.debug("Authentcation header", encodedStr);
return encodedStr;
}catch(err){
log.debug("Error in function authHeaderRestAPI()", err);
}
}