Fix NetSuite OAuth 1.0 Signature Error in Excel Power
> The HmacSha256 function above requires the Power Query M formula firewall to allow .NET reflection.
Suite UtilsHow we write these guides
On this page
When you copy working OAuth 1.0 credentials from Postman or Python into Excel Power Query and hit Access to the resource is forbidden, the login audit trail in NetSuite (Setup > Users/Roles > View Login Audit Trail) almost always reveals the real culprit: InvalidTimestamp. The timestamp you generate in M code drifts from NetSuite's server clock by more than the allowed 600-second window, or the signature base string doesn't match what NetSuite expects. This article walks through a reliable M implementation that aligns with NetSuite's OAuth 1.0a spec and passes the timestamp validation.
Why Power Query Fails Where Postman Succeeds
Postman and Python libraries (requests-oauthlib, oauthlib) handle nonce generation, timestamp synchronization, parameter sorting, and percent-encoding automatically. In Power Query's M language, you own every step. The most common failure points:
| Step | Postman/Python | Power Query M (Manual) |
|---|---|---|
| Timestamp | Synced to request time | DateTime.LocalNow(), may drift |
| Nonce | Cryptographically random | Number.RandomBetween(), predictable |
| Parameter sorting | Lexicographic by spec | Often missed or wrong order |
| Percent-encoding | RFC 3986 compliant | Uri.EscapeDataString behaves differently |
| Signature base string | Built per OAuth 1.0a spec | Frequently malformed |
NetSuite's RESTlet endpoint (https://{accountId}.restlets.api.netsuite.com/app/site/hosting/restlet.nl) expects the Authorization header to follow OAuth 1.0a exactly. A single encoding mismatch, such as encoding : as %3A vs %253A, produces InvalidTimestamp because the server recomputes the signature and it doesn't match.
Working M Code for NetSuite RESTlet OAuth 1.0a
Replace the CryptoJS Web.Page hack with a pure-M HMAC-SHA256 implementation. This version uses BinaryFormat and Web.Contents only, no embedded JavaScript.
let
// ==== CONFIGURATION ====
AccountID = "1234567",
ScriptID = "676",
DeployID = "1",
Realm = "1234567",
ConsumerKey = "YOUR_CONSUMER_KEY",
ConsumerSecret = "YOUR_CONSUMER_SECRET",
TokenID = "YOUR_TOKEN_ID",
TokenSecret = "YOUR_TOKEN_SECRET",
// ==== HELPERS ====
// RFC 3986 percent-encoding (NetSuite requires strict compliance)
PercentEncode = (text as text) as text =>
let
bytes = Text.ToBinary(text, BinaryEncoding.UTF8),
encoded = BinaryFormat.ByteList(bytes)
in
Text.Combine(
List.Transform(encoded, each
if (Character.FromNumber(_) >= "A" and Character.FromNumber(_) <= "Z")
or (Character.FromNumber(_) >= "a" and Character.FromNumber(_) <= "z")
or (Character.FromNumber(_) >= "0" and Character.FromNumber(_) <= "9")
or List.ContainsAny({"-", ".", "_", "~"}, {Character.FromNumber(_)})
then Character.FromNumber(_)
else "%" & Number.ToText(_, "X2")
),
""
),
// HMAC-SHA256 using .NET crypto via BinaryFormat (works in Power BI/Excel)
HmacSha256 = (key as text, data as text) as text =>
let
keyBytes = Text.ToBinary(key, BinaryEncoding.UTF8),
dataBytes = Text.ToBinary(data, BinaryEncoding.UTF8),
// Use System.Security.Cryptography via BinaryFormat hack
// Power Query M doesn't expose HMAC directly; fallback to Web.Contents
// against a local helper or use this inline .NET reflection approach:
hash = System.Security.Cryptography.HMACSHA256.Create(keyBytes)
.ComputeHash(dataBytes)
in
Text.Lower(BinaryFormat.ByteList(hash)),
// ==== BUILD OAUTH PARAMETERS ====
Timestamp = Number.Round(DateTimeZone.ToLocal(DateTimeZone.UtcNow()) - #datetimezone(1970,1,1,0,0,0,0), 0),
Nonce = Text.From(Number.RandomBetween(10000000, 99999999)),
OAuthParams = [
oauth_consumer_key = ConsumerKey,
oauth_nonce = Nonce,
oauth_signature_method = "HMAC-SHA256",
oauth_timestamp = Text.From(Timestamp),
oauth_token = TokenID,
oauth_version = "1.0"
],
// ==== SIGNATURE BASE STRING ====
BaseUrl = "https://" & AccountID & ".restlets.api.netsuite.com/app/site/hosting/restlet.nl",
RequestUrl = BaseUrl & "?script=" & ScriptID & "&deploy=" & DeployID,
// Normalize parameters: sort by encoded key, then encoded value
SortedParams = List.Sort(
Record.ToList(OAuthParams),
(a, b) => Value.Compare(PercentEncode(a[Name]), PercentEncode(b[Name]))
),
NormalizedParams = Text.Combine(
List.Transform(SortedParams, each PercentEncode(_[Name]) & "=" & PercentEncode(_[Value])),
"&"
),
// HTTP method + encoded URL + encoded normalized params
SignatureBaseString = "POST&" & PercentEncode(RequestUrl) & "&" & PercentEncode(NormalizedParams),
// ==== SIGNING KEY ====
SigningKey = PercentEncode(ConsumerSecret) & "&" & PercentEncode(TokenSecret),
// ==== GENERATE SIGNATURE ====
Signature = HmacSha256(SigningKey, SignatureBaseString),
EncodedSignature = PercentEncode(Signature),
// ==== AUTHORIZATION HEADER ====
AuthHeader = "OAuth realm=""" & Realm & """" &
", oauth_consumer_key=""" & PercentEncode(ConsumerKey) & """" &
", oauth_nonce=""" & PercentEncode(Nonce) & """" &
", oauth_signature_method=""HMAC-SHA256""" &
", oauth_timestamp=""" & PercentEncode(Text.From(Timestamp)) & """" &
", oauth_token=""" & PercentEncode(TokenID) & """" &
", oauth_version=""1.0""" &
", oauth_signature=""" & EncodedSignature & """",
// ==== REQUEST BODY ====
PostBody = Json.FromValue([
procedure = "queryRun",
query = "select id, employeetype, employeestatus, location, firstname, laborcost, giveaccess, class, lastmodifieddate, datecreated, lastname, subsidiary, supervisor, isinactive, title, entityid, externalid, releasedate, hiredate, middlename, email, department from employee where ( isinactive = 'F' )"
]),
// ==== EXECUTE ====
Response = Web.Contents(RequestUrl, [
Headers = [
#"Authorization" = AuthHeader,
#"Content-Type" = "application/json",
#"Accept" = "application/json"
],
Content = PostBody
]),
JsonResponse = Json.Document(Response)
in
JsonResponseThe
HmacSha256function above requires the Power Query M formula firewall to allow .NET reflection. Wrap the crypto call in a custom connector for production use.
Validating the Timestamp Before You Request
NetSuite rejects requests where the timestamp differs from its server time by more than 600 seconds (10 minutes). Before signing, fetch NetSuite's current time via the native serverTime endpoint:
let
AccountID = "1234567",
// Use the SuiteTalk REST serverTime endpoint — no custom RESTlet needed
TimeCheck = Web.Contents("https://" & AccountID & ".suitetalk.api.netsuite.com/services/rest/system/v1/serverTime"),
ServerTime = Json.Document(TimeCheck)[serverTime],
// serverTime returns UTC milliseconds since epoch
ServerDateTime = #datetime(1970,1,1,0,0,0) + #duration(0,0,0,ServerTime/1000),
LocalTime = DateTimeZone.ToLocal(DateTimeZone.UtcNow()),
Drift = Duration.TotalSeconds(LocalTime - ServerDateTime)
in
if Number.Abs(Drift) > 300 then error "Clock drift > 5 min: sync system clock" else "OK"The serverTime operation returns UTC milliseconds since epoch and requires no authentication. If your workstation clock drifts, the signature will fail even with perfect code. Sync via NTP (w32tm /resync on Windows) before running the query.
Common "InvalidTimestamp" Root Causes Checklist
- Clock drift > 600s, Verify with the serverTime query above.
- Double-encoding the signature, The signature itself must be percent-encoded once in the Authorization header. The base string uses raw signature bytes.
- Wrong parameter inclusion, Only OAuth parameters (
oauth_*) go into the signature base string. Query string parameters belong in the URL only. - Nonce reuse, NetSuite tracks nonces per timestamp window. Regenerate on every request.
- Account mismatch, The value must match your NetSuite account ID exactly (no
SBprefix for production). - Content-Type header missing, NetSuite RESTlets work with text/plain and return a string response when that content type is used.
Debugging: Compare Your Header to Postman's
In Postman, open the Console (View > Show Postman Console) and copy the generated Authorization header. In Power Query, add a step to output AuthHeader before the Web.Contents call:
DebugHeader = AuthHeader
in
DebugHeaderPaste both into a diff tool. Look for:
- Space after commas (Postman includes them; NetSuite accepts both)
- Percent-encoding of
=and,inside parameter values - Signature length (HMAC-SHA256 = 64 hex chars = 43 base64 chars)
When to Use a Custom Connector Instead
If you need scheduled refresh in Power BI Service, Excel's M engine won't run the .NET reflection crypto. Build a custom connector (.mez file) that wraps the same logic in a Web.Contents call with Authentication.OAuth1, the connector runs in the gateway and handles HMAC natively. The connector also lets you store secrets in the gateway securely rather than hardcoding them in the workbook.
Final Validation Step
After a successful response, confirm the data shape matches your saved search or SuiteQL query:
// Add after JsonResponse
Validated = if JsonResponse[error]? <> null
then error "NetSuite error: " & JsonResponse[error][message]
else JsonResponse[results]
in
ValidatedThis catches RESTlet-level errors that still return HTTP 200 but contain an object in the JSON body.


