菜单
开源

HTTP 认证

关于如何在负载测试中使用不同身份验证或授权方法的脚本示例。

基本认证

JavaScript
import encoding from 'k6/encoding';
import http from 'k6/http';
import { check } from 'k6';

const username = 'user';
const password = 'passwd';

export default function () {
  const credentials = `${username}:${password}`;

  // Passing username and password as part of the URL will
  // allow us to authenticate using HTTP Basic Auth.
  const url = `https://${credentials}@quickpizza.grafana.com/api/basic-auth/${username}/${password}`;

  let res = http.get(url);

  // Verify response
  check(res, {
    'status is 200': (r) => r.status === 200,
    'is authenticated': (r) => r.json().authenticated === true,
    'is correct user': (r) => r.json().user === username,
  });

  // Alternatively you can create the header yourself to authenticate
  // using HTTP Basic Auth
  const encodedCredentials = encoding.b64encode(credentials);
  const options = {
    headers: {
      Authorization: `Basic ${encodedCredentials}`,
    },
  };

  res = http.get(`https://quickpizza.grafana.com/api/basic-auth/${username}/${password}`, options);

  // Verify response (checking the echoed data from the QuickPizza
  // basic auth test API endpoint)
  check(res, {
    'status is 200': (r) => r.status === 200,
    'is authenticated': (r) => r.json().authenticated === true,
    'is correct user': (r) => r.json().user === username,
  });
}

NTLM 认证

JavaScript
import http from 'k6/http';

const username = 'user';
const password = 'passwd';

export default function () {
  // Passing username and password as part of URL and then specifying
  // "ntlm" as auth type will do the trick!
  const credentials = `${username}:${password}`;
  const res = http.get(`http://${credentials}@example.com/`, { auth: 'ntlm' });
}

使用 k6-jslib-aws 进行 AWS Signature v4 认证

为了使用 AWS Signature Version 4 对 AWS API 的请求进行身份验证,k6 提供了 k6-jslib-aws JavaScript 库,它提供了一个专用的 SignatureV4 类。这个类可以生成经过认证的请求,以便使用 http k6 模块发送到 AWS API。

这是一个示例脚本,演示如何签名请求以从 S3 存储桶获取对象

JavaScript
import http from 'k6/http';
import {
  AWSConfig,
  SignatureV4,
} from 'https://jslib.k6.io/aws/0.13.0/signature.js';

const awsConfig = new AWSConfig({
  region: __ENV.AWS_REGION,
  accessKeyId: __ENV.AWS_ACCESS_KEY_ID,
  secretAccessKey: __ENV.AWS_SECRET_ACCESS_KEY,

  /**
   * Optional session token for temporary credentials.
   */
  sessionToken: __ENV.AWS_SESSION_TOKEN,
});

export default function () {
  /**
   * Create a signer instance with the AWS credentials.
   * The signer will be used to sign the request.
   */
  const signer = new SignatureV4({
    service: 's3',
    region: awsConfig.region,
    credentials: {
      accessKeyId: awsConfig.accessKeyId,
      secretAccessKey: awsConfig.secretAccessKey,
      sessionToken: awsConfig.sessionToken,
    },
  });

  /**
   * Use the signer to prepare a signed request.
   * The signed request can then be used to send the request to the AWS API.
   */
  const signedRequest = signer.sign(
    {
      method: 'GET',
      protocol: 'https',
      hostname: 'test-jslib-aws.s3.us-east-1.amazonaws.com',
      path: '/bonjour.txt',
      headers: {},
      uriEscapePath: false,
      applyChecksum: false,
    },
    {
      signingDate: new Date(),
      signingService: 's3',
      signingRegion: 'us-east-1',
    }
  );

  /**
   * The `signedRequest` object contains the signed request URL and headers.
   * We can use them to send the request to the AWS API.
   */
  http.get(signedRequest.url, { headers: signedRequest.headers });
}