How to use NetSuite REST API with OAuth 2 and C# .NET

Eric Popivker
ENTech Solutions
Published in
6 min readOct 18, 2022

In this article, we will go over various approaches to authorize access to NetSuite REST APIs. We will objectively pick the preferred approach. After that, we will go over the steps to get this approach working both on the server and client side.

Auth to NetSuite REST APIs

To authenticate/authorize with NetSuite REST API, there are several approaches:

  • Token Based Authentication
  • OAuth 2 Standard (Authorization Code Grant)
  • OAuth 2 Machine to Machine

Token-based authentication (TBA) is still widely used in the NetSuite ecosystem. It resembles OAuth 1 spec and is a bit outdated. For new projects, it is best to use something more recent like OAuth 2.

There are two ways to authenticate with OAuth 2 in NetSuite. The standard way, also called Authorization Code Grant, opens a browser where the user explicitly needs to authorize an application to access NetSuite API.

The second way is called “machine to machine” and doesn’t require user interaction.

The Way of OAuth 2

The standard OAuth 2, where the user authorizes app access in the browser, works great in NetSuite. When you authorize — you get AccessToken and RefreshToken, which is pretty standard. AccessToken expires in 60 mins, so you need to keep using RefreshToken to obtain new AccessToken after it is expired, which is also pretty typical.

What is not normal is that RefreshToken is only valid for 7 days, so after 7 days, you need to re-ask the end-user to consent to access your application. And keep doing that every 7 days (every week!!!). That can become a bit of a nuisance.

The solution is to use the second OAuth 2 approach called “Machine to Machine,” which bypasses User Interaction altogether. This flow is based on creating a certificate valid for 2 years. Access Token created using this certificate will still expire every hour, but at least you can easily recreate it for 2 years, unlike the RefreshToken, which is limited to 7 days.

OAuth 2 — Machine to Machine Setup Steps

To enable Machine to Machine Authentication, you need to take the following steps:

  1. Create new integration with M2M flag enabled
  2. Create certificate locally
  3. Setup client credentials in NetSuite

This video does a great job of going through all the steps to get M2M working: very nice video

Enjoy this masterpiece, but please come back to create a Certificate in Windows using NetSuite REST API through C#.

Creating a Certificate in Windows

One part of the instructions that is not exactly clear is creating a certificate.

Here is how to do it in Windows.

First, you need to install OpenSSL for windows.

Go to page: https://slproweb.com/products/Win32OpenSSL.html

and download Win64 OpenSSL v3.0.5 Light (or Win32, if you have time-traveled from the early 2000s).

Install it on your computer. I installed it to D:\Tools\OpenSSL-Win64.

Secondly, you need to run the OpenSSL command to create a certificate.

Here is a small batch script to do it:

SET OpenSslExe="D:\Tools\OpenSSL-Win64\bin\OpenSsl.exe"
SET OutputDir="D:\Temp\NetSuite"
CD %OutputDir%%OpenSslExe% req -x509 -newkey rsa:3072 -keyout sw2021d_key.pem -out sw2021d_cert.pem -days 365 -nodespause

Locally create a batch file like “Run.bat,” and copy the script above to this file. Change the OpenSllExe path to point to the location of OpenSsl.exe and set OutputDir to the directory where you would like to save the certificate. After that, run the bat file by double-clicking on it in explorer or through CMD if you are over 25 years old.

When running the command, it will ask you to enter various info like country, and city. You can just use default values by pressing the ENTER key.

After entering all the info, the openssl will exit, and you will have two files in the output folder:

sw2021d_cert.pem
sw2021d_key.pem

You can use certificate “.._cert.pem file to load it into NetSuite. As to the key file “…_key.pem”, we will use it a bit later when generating JwtToken with C#.

Calling NetSuite API with C#

Here is a demo project that shows how to use M2M authentication in C#. https://github.com/ericpopivker/entech-blog-netsuite-oauth-m2m-demo/tree/main/NetSuiteOauthM2mDemo

Core logic is in file NetSuiteApiClient.cs.

First, you need to fill out a bunch of constants specific to your account:

private const string AccountId = "XXXXX-sb1";         
private const string ClientCredentialsCertificateId = "XXXXX"; private string ApiConsumerKey = "XXXXX";
private const string PrivateKeyPem = @"-----BEGIN PRIVATE KEY-----XXXXX-----END PRIVATE KEY-----";

AccountId comes from url when you are using NetSuite.

So, in this case, AccountId is “5534243-sb1”.

ClientCredentialsCertificateId is the certificate id that is displayed when you upload the certificate to Client Credentials:

ApiConsumerKey is from the page where you create M2M integration:

And last by not least PrivateKeyPem is from the “..key.pem” file that we created earlier using OpenSSL:

Just open the “..key.pem” file in notepad and copy the whole content into “PrivateKeyPem” variable.

Getting AccessToken

The main part of the logic is getting an access tokens using the parameters we specified above.

public async Task<string> GetAccessToken()
{
var url = Oauth2ApiRoot + "/token/";
string clientAssertion = GetJwtToken(); var requestParams = new List<KeyValuePair<string, string>>();
requestParams.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
requestParams.Add(new KeyValuePair<string, string>("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"));

requestParams.Add(new KeyValuePair<string, string>("client_assertion", clientAssertion));
using var httpRequest =
new HttpRequestMessage(HttpMethod.Post, url);
httpRequest.Content = new FormUrlEncodedContent(requestParams);
var httpResponse = await _httpClient.SendAsync(httpRequest); var responseJson = await
httpResponse.Content.ReadAsStringAsync();
var response = JsonSerializer.Deserialize<NsToken>(responseJson); return response.access_token;
}

This code calls GetJwtToken() which uses RSA encryption to generate JwtToken. After that we use HttpClient to call

https://{AccountId}.suitetalk.api.netsuite.com/services/rest/auth/oauth2/v1

with jwtToken and several other parameters specified in NetSuite documentation, to get AccessToken.

When we have AccessToken can use Bearer authentication to call any NetSuite REST API endpoint until the token expires in about 1 hour. When it expires, just call GetAccessToken() again (and again and again).

Testing

To ensure that the code works with your API, there is a test project with NetSuiteApiClientsTest.cs class.

[Test]public async Task GetAccessToken_ReturnsValidToken(){   var nsApiClient = new NetSuiteApiClient();   var accessToken = await nsApiClient.GetAccessToken();   Assert.IsNotEmpty(accessToken);}[Test]public async Task FindCustomerIds_LimitTwo_TwoIds(){   var nsApiClient = new NetSuiteApiClient();   var ids = await nsApiClient.FindCustomerIds(2);   Assert.AreEqual(2, ids.Count);}[Test]public async Task GetCustomer_ValidId_ReturnsCustomer(){   var nsApiClient = new NetSuiteApiClient();   var customer = await nsApiClient.GetCustomer(125173);   Assert.IsNotNull(customer);
}

The 3 tests in this class:

  • check that GetAccessToken works
  • call FindCustomerIds API endpoint with 2 as limit and checks that 2 customers are returned
  • test for GetCustomer by Id. CustomerId is hardcoded, so change Id (currently 125173) to your valid customerId to get this working

Conclusion

In this article, we went over various ways to Auth with NetSuite REST API. We selected Oauth2 M2M as the best choice for most scenarios and went deep into C# code, allowing us to connect and use NetSuite REST API.

The code is available on GitHub here:

https://github.com/ericpopivker/entech-blog-netsuite-oauth-m2m-demo/tree/main/NetSuiteOauthM2mDemo

About Us

ENTech Solutions specializes in integrating NetSuite to Salesforce, Hubspot, and any other app imaginable. We are experts in Celigo, MuleSoft, Boomi, and custom NetSuite integrations. If you have an integration project that you need to be completed to the top industry standards, please contact us by email: hello@entechsolutions.com.

--

--

Eric Popivker
ENTech Solutions

Living in .NET world for 20+ years. Founder of .NET Fiddle.