You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用K6上传文件至Azure Blob Storage时遭遇AuthenticationFailed认证错误求助

K6上传文件至Azure Blob Storage时遭遇AuthenticationFailed认证错误求助

我正在用K6做性能测试,其中需要连接并上传文件到Azure Blob容器,但脚本一直因为头部不匹配导致认证失败——尽管我反复检查过头部信息是一致的。我收到的错误响应如下:

ERRO[0001] Response Body:

return (<Code>AuthenticationFailed</Code>)
Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

RequestId:XXXXXXX

Time:2025-01-10T22:02:41.3196583ZThe MAC signature found in the HTTP request 'xxxxxxx' is not the same as any computed signature. Server used following string to sign: 'PUT

这是我运行的K6脚本,有没有人之前做过这个场景的测试或者遇到过类似问题呀?

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

export const options = {
 stages: [{
        duration: '1m',
        target: 1
    },
    {
        duration: '10m',
        target: 1
    },
    {
        duration: '1m',
        target: 0
    },
],
};

// Environment variables
const storageAccount = __ENV.STORAGE_ACCOUNT;
const containerName = __ENV.CONTAINER_NAME;
const accountKey = __ENV.ACCOUNT_KEY;

if (!storageAccount || !containerName || !accountKey) {
  throw new Error("Missing STORAGE_ACCOUNT, CONTAINER_NAME, or ACCESS_KEY environment variables.");
}

// Function to compute HMAC SHA256 signature
function signWithAccountKey(stringToSign, accountKey) {
  console.log("Raw Account Key:", accountKey);
  const decodedKey = encoding.b64decode(accountKey);
  console.log("Decoded Account Key (Hex):", Array.from(decodedKey).map((byte) => byte.toString(16).padStart(2, '0')).join('')); // Log decoded key

  const hmac = crypto.createHMAC('sha256', decodedKey);
  hmac.update(stringToSign, 'utf8');
  const signature = hmac.digest('base64');
  console.log("Generated Signature:", signature); // Log the generated signature
  return signature;
}


// Function to generate the Authorization header
function generateAuthorizationHeader(verb, urlPath, headers) {
 const canonicalizedHeaders = Object.keys(headers)
    .filter((key) => key.startsWith('x-ms-'))
    .sort()
    .map((key) => `${key}:${headers[key]}\n`)
    .join('');

  const canonicalizedResource = `/${storageAccount}${urlPath}`;

  const stringToSign = [
    verb,
    '', // Content-Encoding
    '', // Content-Language
    headers['Content-Length'] || '', // Content-Length
    '', // Content-MD5
    headers['Content-Type'] || '', // Content-Type
    '', // Date (not used because we use x-ms-date)
    '', // If-Modified-Since
    '', // If-Match
    '', // If-None-Match
    '', // If-Unmodified-Since
    '', // Range
    canonicalizedHeaders,
    canonicalizedResource,
  ].join('\n');

  // Log the StringToSign for debugging
  console.log("StringToSign:\n" + stringToSign);

  const signature = signWithAccountKey(stringToSign, accountKey);
  return `SharedKey ${storageAccount}:${signature}`;
}

// Base URL and content
const baseUrl = `https://${storageAccount}.blob.core.windows.net/${containerName}`;
const fileContent = 'A'.repeat(1024 * 1024 * 100); // 100 MB file content

export default function() {
  const fileName = `test-${__VU}-${__ITER}.xml`;
  const urlPath = `/${containerName}/${fileName}`;
  const url = `${baseUrl}/${fileName}`;
  const date = new Date().toUTCString();

  const headers = {
    'x-ms-date': date,
    'x-ms-version': '2020-10-02',
    'x-ms-blob-type': 'BlockBlob',
    'Content-Type': 'application/xml',
    'Content-Length':  fileContent.length.toString(),
  };

  headers['Authorization'] =  generateAuthorizationHeader('PUT', urlPath, headers);

  // Log headers for debugging
  console.log("Authorization Header:", headers['Authorization']);
  console.log("Headers Sent:", JSON.stringify(headers));

  const res = http.put(url, fileContent,     {
    headers
  });

  const success = check(res, {
    'Upload succeeded': (r) => r.status === 201,
  });

  if (!success) {
    console.error(`Upload failed for ${fileName}`);
    console.error(`Status: ${res.status}`);
    console.error(`Response Body: ${res.body}`);
    console.error(`Headers Sent: ${JSON.stringify(headers)}`);
  }
}

备注:内容来源于stack exchange,提问作者Mayamiko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 13:39:34