How do I make an Oauth2 REST request using Node and node-rest-client?

860 Views Asked by At

I'm trying to copy the example POST request from the documentation (https://www.npmjs.com/package/node-rest-client, https://www.npmjs.com/package/node-rest-client#basic-http-auth). How do I encode this curl request in Node?

$ curl -u user:password localhost:8080/oauth/token -d grant_type=client_credentials
{"access_token":"c6b53866-b38a-41f9-878c-87bb280ca9d8","token_type":"bearer","expires_in":43199,"scope":"write"}

I have this

var oauth = {
    data: { grant_type: "client_credentials" },
    headers: { "Content-Type": "application/json" }
};
var options_auth = { user: "user", password: "password" };
var client = new Client(options_auth);

client.post("http://127.0.0.1:8080/oauth/token", oauth, function (data, response) {
    // parsed response body as js object
    console.log(data);

But it gives me an error

[2019-10-15T00:40:23.780Z] { error: 'invalid_request', error_description: 'Missing grant type' }

The OAuth server is Spring Boot for what it's worth.

1

There are 1 best solutions below

0
On

I had to change the headers value:

    headers: { "Content-Type": "application/x-www-form-urlencoded" }

Now it gave me an access token:

[2019-10-15T00:58:15.354Z] {                           
  access_token: 'c6b53866-b38a-41f9-878c-87bb280ca9d8',
  token_type: 'bearer',                                
  expires_in: 41873,                                   
  scope: 'write'                                       
}