OAuth 2.0访问令牌请求不起作用

时间:2019-02-09 18:37:32

标签: javascript node.js oauth-2.0

我正在使用Okta示例OAuth 2.0“客户端凭据” M2M请求,

https://developer.okta.com/blog/2018/06/06/node-api-oauth-client-credentials

此示例是一个简单的javascript node.js示例,其中Web服务为index.js,localhost:3000和一个名为test.js的测试客户端。 test.js成功获取Okta OAuth访问令牌。但是,我似乎可以将客户端请求test.js发送到Web服务,以使其正常工作。下面是test.js代码,

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()

就像我说的那样,test.js能够毫无问题地获取Okta的访问令牌。  但是,我不断从Web服务请求的test.js中收到“ Test_Error:错误:解析错误”。我调试了代码,发现错误来自test.js http://localhost:3000“请求。这是test.js的try / catch捕获错误的部分,

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

控制台输出如下,

>node test.js
Bearer eyJraWQiOiJoai1TdEl6eDlaUmRoaFpNeUlCalpRSkg2N3lsYkRCcmdJZ191ZkpycVZBIiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULjJiVkNjTWEyWFlQTWhJWjdNUGx0TTRQeTV3WE9EU3ZjUUIyZVJaNkNvN2MiLCJpc3MiOiJodHRwczovL2phYmlsc2ttLm9rdGEuY29tL29hdXRoMi9hdXNhYzZ6NThoZmFyVTQzUzM1NiIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6MzAwMCIsImlhdCI6MTU0OTczNjk4MywiZXhwIjoxNTQ5ODIzMzgzLCJjaWQiOiIwb2FhY2FxNzZqQjFWNjBMODM1NiIsInNjcCI6WyJzdWNoX3Njb3BlIl0sInN1YiI6IjBvYWFjYXE3NmpCMVY2MEw4MzU2In0.HOw6LLKDMJ0uaLSAVoUgLCvkCzpts1I4miF25J3fjKzTCd7ZPSgYbfVNTA7pdAwnxuxTR1YMS1Asn47BDKIHolqr4EZxgLBXdJQmLTDW1gZaCesPFPV1RH5WzRYjYpo923DxSkBaRU_ayD1g8DQitGnSy_oOqzbGgTKdfPTQDRIOh8G3aXBqO6s6fb6eukmm_OdT_NkuLg95AhehuNO_m5eook_Y4PYsYLiHC8KblrgZYDifrJV_RAC7SCgoiKLhR2RL6x8bvrQOqjaRTh1ZeEd2P3zCQJ_sL3xck_pCH59b57MlX_5kpcyewfJeVICl00Xmuj45j-aoX8IQEPX08g
Error: Error: Parse Error

永远不会向index.js发出请求。在我看来,在发出http请求之前,我得到了某种标题语法“ Parse Error”。有什么想法吗?

谢谢...

0 个答案:

没有答案