首页 > 解决方案 > 如何使用 client-oauth2 作为 json 发送?

问题描述

所以我有这个代码

    const auth0 = new ClientOAuth2({
        clientId: 'my id',
        clientSecret: 'my secret',
        accessTokenUri: 'https://myorg.auth0.com/oauth/token',
        scopes: ['version:read']
    });

    auth0.credentials.getToken().then(tok => {
        console.log(tok);
    }).catch(e => console.log(e));

但我收到了 403

这就是 auth0 建议我发送的内容

 calebcushing$ curl --request POST   --url https://myorg.auth0.com/oauth/token   --header 'content-type: application/json'   --data '{"client_id":"my id","client_secret":"my secret","audience":"http://localhost:4000","grant_type":"client_credentials"}'
curl 'https://myorg.auth0.com/oauth/token' -H 'authority: myorg.auth0.com' -H 'accept: application/json, application/x-www-form-urlencoded' -H 'origin: http://localhost:3000' -H 'authorization: Basic encoded' -H 'content-type: application/x-www-form-urlencoded'  --data 'scope=version%3Aread&grant_type=client_credentials'

我没有结婚,client-oauth2所以如果另一个图书馆是更好的选择,那很好。我更喜欢使用 oauth 库,所以我不必做所有的协调舞蹈。如果在向资源服务器发出请求时它会自动重新获取令牌等,则可以加分。

标签: typescriptauth0

解决方案


如果我理解正确,我认为您正在尝试执行客户端凭据授予类型并获取 Auth0 管理 API 令牌。您可以使用 auth0 节点 sdk ( auth0 )。

安装包:

npm install auth0


var AuthenticationClient = require('auth0').AuthenticationClient;

var auth0 = new AuthenticationClient({
  domain: '{YOUR_ACCOUNT}.auth0.com',
  clientId: '{CLIENT_ID}',
  clientSecret: '{CLIENT_SECRET}'
});

auth0.clientCredentialsGrant(
  {
    audience: 'https://{YOUR_ACCOUNT}.auth0.com/api/v2/',
    scope: '{MANAGEMENT_API_SCOPES}'
  },
  function(err, response) {
    if (err) {
      // Handle error.
    }
    console.log(response.access_token);
  }
);

您还可以使用任何 HTTP 客户端。例如,获取或请求。

https://auth0.com/docs/api-auth/tutorials/client-credentials


推荐阅读