OAuth 2.0 Client Credentials Example Not Working


#1

Hello,

I am using one of the Okta Developer examples, “Secure a Node API with OAuth 2.0 Client Credentials”, https://developer.okta.com/blog/2018/06/06/node-api-oauth-client-credentials. This example is a simple javascript node.js example with the web service called index.js and a test client called test.js. test.js is successful in obtaining Okta OAuth access token. However, I can’t seem to get the client request, test.js, to the web service to work correctly. Below is the test.js code,

require(‘dotenv’).config()
const request = require(‘request-promise’)
const btoa = require(‘btoa’)
const { ISSUER, TEST_CLIENT_ID, TEST_CLIENT_SECRET, DEFAULT_SCOPE } = process.env

const test = async () => {
const token = btoa(${TEST_CLIENT_ID}:${TEST_CLIENT_SECRET})
try {
const { token_type, access_token } = await request({
uri: ${ISSUER}/v1/token,
json: true,
method: ‘POST’,
headers: {
authorization: Basic ${token},
},
form: {
grant_type: ‘client_credentials’,
scope: DEFAULT_SCOPE,
},
})

console.log([token_type, access_token].join(' '))
const response = await request({
  uri: 'http://localhost:3000',
  json: true,
  headers: {
    authorization: [token_type, access_token].join(' '),
  },
})

console.log(response)

} catch (error) {
console.log(Error: ${error.message})
}
}

test()

Like I said, test.js is able to obtain the access token for Okta with no issues. However I keep getting a “Test_Error: Error: Parse Error” from test.js on the web service request. I have debugged the code and find that the error is coming from the test.js, http://localhost:3000" request. Here is the section of the test.js where the try/catch is catching the error,

console.log([token_type, access_token].join(’ ‘))
const response = await request({
uri: ‘http://localhost:3000’,
json: true,
headers: {
authorization: [token_type, access_token].join(’ '),
},
})

Console output looks follows,

node test.js

Bearer jraWQ…

Error: Error: Parse Error

The request is never made to index.js. It looks to me that I am getting some sort of header syntax “Parse Error” before the http request is being made. Any ideas? By the way I copied the Bearer token output from my screen and did a curl command,

curl -i http://localhost:3000 -H “Authorization: Bearer jraWQ…”

The index.js server correctly acknowledged the token and I get a “Hello World”


#2

Hi @skmansfield

In the code

console.log([token_type, access_token].join(’ ‘))
const response = await request({
uri: ‘http://localhost:3000’,
json: true,
headers: {
authorization: [token_type, access_token].join(’ '),
},
})

you have at join(’ ') two different quotation marks. If you modify them, it should work successfully.


#3

Good catch on the quotations. Got to get new glasses. Unfortunately this did not work. I still get the Parse Error with the correct quotations. Any new ideas?