如何使用 Artillery 自动生成 OAuth 2.0 令牌?

How to automate the OAuth 2.0 token generation using Artillery?

我想通过 javascript 自动自动化 OAuth 2.0 令牌。我有什么办法可以做到这一点并获得令牌以在火炮脚本中使用它。

对于 OAuth 令牌生成,我有以下详细信息:

这是通过客户端身份验证凭据完成的。

下面是我用来生成令牌的示例代码:

var ClientOAuth2 = require('client-oauth2')

var Auth = new ClientOAuth2({
  clientId: 'ClientID',
  accessTokenUri: 'https://Auth_URL/v2.0/token',
  authorizationUri: 'https://Auth_URL/v2.0/authorize',
  redirectUri: 'https://Auth_URL/',
  scope: 'api://Scope/access_as_user'
})




  Auth.owner.getToken('Username', 'password')
  .then(async (user) => {
    await console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
  }).catch((e) => { console.log('error show',e); })
  .finally( () => console.log('end'));

您可以声明您的自定义 JS 文件,该文件将在每次请求之前触发:

您的 YAML 文件可以如下所示:

config:
  target: "https://baseUrl.com"
  phases:
    - duration: 60
      arrivalRate: 100
  processor: "./customFile.js"

scenarios:
  - flow:
      - post:
          url: "/pathInYourApi"
          headers:
            Content-Type: "application/json"
            Accept: application/json
          json: {}
          beforeRequest: "beforeRequest"

然后是您的 customFile.js 脚本:

module.exports = {
  beforeRequest: beforeRequest,
};

function beforeRequest(requestParams, context, ee, next) {
  // Call your OAuth client, and after you obtain token you can assign it to requestParams Authorization header
  // eg. requestParams.headers.Authorization = `Bearer + ${token}`

  return next(); // MUST be called for the scenario to continue
}