K6-身份验证-获取身份验证令牌



我有一个mocha javascript文件,其中我有require函数,可以在无头浏览器模式下登录到应用程序,使用crendentials登录并返回jwt身份验证。

我想通过K6调用这个脚本。但据我所知,从K6调用节点模块java脚本是不可能的吗?

有其他选择吗?

我也刚刚开始实现k6,还有同样的步骤要做;(以下是我的做法。

  • 您需要知道如何对要使用的API进行身份验证。我想我们已经有了,正如您所写的,您希望使用节点模块
  • 第二,使用适当的方法与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();
})
}