'How to implement oAuth 2.0 client credentials flow in NetSuite. As i am getting 400 Bad Request below is the code that i tried in dotnet
Hi All can anyone help me out on this.
I have done below steps
Created a self signed cert:
openssl req -x509 -newkey rsa:4096 -sha256 -keyout auth-key.pem -out auth-cert.pem -nodes -days 730
Added the auth-cert.pem to the integration in NetSuite and able to create integration record
Tried calling the TokenUrl endpoint to get access token
I keep getting Bad Request (Status code 400) when I call GetNSAccessToken(string signedJWTAssertion) to get access token from TokenUrl.
below is the code tried in c#.net
static void Main(string[] args)
{
var jwt = GenerateNSJWTPEMFile("auth-key.pem");
var accessToken = GetNSAccessToken(signedJWTAssertion: jwt);
}
public static string GenerateNSJWTPEMFile(string PEMFile)
{
var tokenHandler = new JwtSecurityTokenHandler();
var rsaPem = File.ReadAllText(PEMFile);
var privatekey = RSA.Create();
privatekey.ImportFromPem(rsaPem);
var key = new RsaSecurityKey(privatekey);
var signingCredentials = new SigningCredentials(
key: key,
algorithm: SecurityAlgorithms.RsaSha256
);
var Now = DateTimeOffset.UtcNow;
var Exp = Now.AddMinutes(30).ToUnixTimeSeconds();
var Iat = Now.ToUnixTimeSeconds();
var Scope = "restlets";
var Aud = "https://xxxxxxx-sb2.suitetalk.api.netsuite.com/services/rest/auth/oauth2/v1/token";
var Issuer = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var jwt = new SecurityTokenDescriptor
{
Issuer = Issuer,
Claims = new Dictionary<string, object>()
{
["iss"] = Issuer,
["scope"] = Scope,
["aud"] = Aud,
["exp"] = Exp,
["iat"] = Iat
},
SigningCredentials = signingCredentials
};
var jws = tokenHandler.CreateToken(jwt);
var encoded = new JwtSecurityTokenHandler().WriteToken(jws);
return encoded;
}
public static string GetNSAccessToken(string signedJWTAssertion)
{
string accessToken;
string TokenUrl = "https://xxxxxxx-sb2.suitetalk.api.netsuite.com/services/rest/auth/oauth2/v1/token";
HttpClient _httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Clear();
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),
new KeyValuePair<string, string>("client_assertion", signedJWTAssertion)
};
using (var content = new FormUrlEncodedContent(requestParams))
{
var response = _httpClient.PostAsync(TokenUrl, content).Result;
var responseContent = response.Content.ReadAsStringAsync().Result;
accessToken = responseContent;
}
return accessToken;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
