Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating OAuth 2.0 Access Token with JavaScript

I'm trying to generate OAuth 2.0 Tokens via OneLogin's API. I read through their documentation and was able to set up Postman to test, and grab the access tokens successfully.

However, when I try to do the same request programmatically via JavaScript fetch, it doesn't work.

Code:

function getAuthToken() {
  // POST Request (To get Access Token)
  var url = 'https://api.us.onelogin.com/auth/oauth2/v2/token?grant_type=client_credentials' 

  var postOptions = {
    'method': 'POST',
    'headers': {
      'Content-Type': 'application/json; charset=utf-8',
      'Authorization' : 'client_id:xxxx, client_secret:xxxx'
    },
    'redirect': 'follow'
  };
 var authToken = UrlFetchApp.fetch(url, postOptions);
}

Error

Error message

The error message indicates that grant_type is missing, but I'm passing the grant_type argument in the body of the POST request as a string (raw) like the documentation requires, and I'm still receiving the error. I even tried to write '{"grant_type": "client_credentials"}' in-line with the 'body' parameter, but still receive the same error message.

Any ideas? Thank you in advance!

like image 906
rynoknows Avatar asked Nov 06 '25 06:11

rynoknows


1 Answers

You are using a JSON encoding for the parameters. The access token request must send the form parameters using application/x-www-form-urlencoded encoding.

See the OAuth2 standard here: https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3

like image 191
MvdD Avatar answered Nov 09 '25 08:11

MvdD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!