Sample Module Code for Getting Amazon Cognito Access Token with k6 Load Testing Tool
I’ll introduce sample module code for getting Amazon Cognito Access Token with the k6 load testing tool.
In the k6 load testing tool, setup and teardown processing before and after the main load test processing are performed with export function setup()
and export function teardown()
respectively.
? Reference: Test lifecycle
.envrc
export AWS_COGNITO_CLIENT_ID=
export AWS_COGNITO_USERNAME=
export AWS_COGNITO_PASSWORD=
export MY_K6_BASE_URL=http://localhost:3000
auth_cognito.js
import http from 'k6/http';
export function auth() {
const headers = {
'x-amz-target': 'AWSCognitoIdentityProviderService.InitiateAuth',
'content-type': 'application/x-amz-json-1.1',
};
const res = http.post('https://cognito-idp.ap-northeast-1.amazonaws.com/',
JSON.stringify({
AuthFlow: 'USER_PASSWORD_AUTH',
ClientId: `${__ENV.AWS_COGNITO_CLIENT_ID}`,
AuthParameters: {
USERNAME: `${__ENV.AWS_COGNITO_USERNAME}`,
PASSWORD: `${__ENV.AWS_COGNITO_PASSWORD}`
},
ClientMetadata: {}
}), {
headers: headers,
});
const resJson = JSON.parse(res.body);
return resJson.AuthenticationResult.AccessToken;
}
import http from 'k6/http';
import { auth } from './auth_cognito.js';
export function setup() {
console.log('setup');
return auth();
}
export default function (accessToken) {
const query = `
query viewer {
login
}
`;
const headers = {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
};
const res = http.post(`${__ENV.MY_K6_BASE_URL}/graphql`,
JSON.stringify({
query: query,
}), {
headers: headers,
});
console.log(JSON.parse(res.body));
}
export function teardown(data) {
console.log('teardown');
}
That’s all from the Gemba.