K6 - 认证 - 获取认证令牌

3
我有一个Mocha JavaScript文件,其中有一个require函数用于在无头浏览器模式下登录应用程序,使用凭据登录并返回JWT身份验证。
我想通过K6调用此脚本。但是据我所知,从K6调用Node模块JavaScript是不可能的?
这方面有没有其他替代方法?
1个回答

7

我也刚开始使用k6,需要完成相同的步骤 ;) 以下是我的实现方式。

  • 首先,您需要知道如何对要使用的API进行身份验证。 我假设我们已经拥有它,因为您写道您想要使用node模块。
  • 其次,使用适当的方法与API通信
  • 接下来,捕获令牌并将其附加到下一个请求头中
  • 最后,使用所需的请求测试API

我在k6 API示例网页上找到了代码片段。 我稍微简化了示例代码,并得到了以下结果:

import {
  describe
} from 'https://jslib.k6.io/functional/0.0.3/index.js';
import {
  Httpx,
  Request,
  Get,
  Post
} from 'https://jslib.k6.io/httpx/0.0.2/index.js';
import {
  randomIntBetween,
  randomItem
} from "https://jslib.k6.io/k6-utils/1.1.0/index.js";

export let options = {
  thresholds: {
    checks: [{
      threshold: 'rate == 1.00',
      abortOnFail: true
    }],
  },
  vus: 2,
  iterations: 2
};

//defining auth credentials
const CLIENT_ID = 'CLIENT_ID';
const CLIENT_SECRET = 'CLIENT_SECRET';
let session = new Httpx({
  baseURL: 'https://url.to.api.com'
});

export default function testSuite() {

  describe(`01. Authenticate the client for next operations`, (t) => {

    let resp = session.post(`/path/to/auth/method`, {
      //this sections relays on your api requirements, in short what is mandatory to be authenticated
      grant_type: GRANT_TYPE,
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
    });

    //printing out response body/status/access_token - for debug
    //    console.log(resp.body);
    //    console.log(resp.status);
    //    console.log(resp.json('access_token'));

    //defining checks
    t.expect(resp.status).as("Auth status").toBeBetween(200, 204)
      .and(resp).toHaveValidJson()
      .and(resp.json('access_token')).as("Auth token").toBeTruthy();


    let authToken = resp.json('access_token');
    // set the authorization header on the session for the subsequent requests.
    session.addHeader('Authorization', `Bearer ${authToken}`);

  })

  describe('02. use other API method, but with authentication token in header ', (t) => {

    let response = session.post(`/path/to/some/other/post/method`, {
      "Cache-Control": "no-cache",
      "SomeRequieredAttribute":"AttributeValue"
    });


    t.expect(response.status).as("response status").toBeBetween(200, 204)
      .and(response).toHaveValidJson();
  })

}


谢谢你在这里的帮助。正如你所推测的,我正在尝试通过 UI 进行身份验证,而不是使用 API。我不知道这是否会对我有所帮助。 - Jay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接