从打字稿中的 Set-Cookie header 获取 jwt 值

fetch the jwt value from Set-Cookie header in typescript

我正在使用 javascript k6 负载测试工具向我们的应用程序服务器发出 http.post 请求。

服务器向我发送了一个响应,它也发送了响应headers。

其中一个回复 header 是下面 Set-Cookie header 发回给我的: Set-Cookie:xx00000000xxxxxxxxxx0000000000xx-jwt=;路径=/; expires=2021 年 4 月 23 日,星期五 04:15:19 GMT;域名=.somedomain.com;同一站点=none;安全

为了通过我的 k6 测试工具向我的服务器发出后续请求 - 我想解析上面的 Set-Cookie 值并仅获取 的 jwt 值并存储在一个变量中喜欢 => fetched_jwt=

我如何从 Set-Cookie header 中获取 jwt 的值,这些值有多个由服务器发回给我的值?

根据 MDN,Set-Cookie 语法是这样的

Set-Cookie: <cookie-name>=<cookie-value>
// and also can be followed by other attribute
Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly
// but no matter what attributes behind it, cookie name and value will be on first

所以,如果你想解析它,只需要获取第一个属性。可以用String.prototype.split(),然后得到第一个

const myCookie = unparsedCookie.split(';')[0];

并再次使用 String.prototype.split() 获取其名称和值。

const [name, value] = myCookie.split('=');

const unparsedCookie = 'xx00000000xxxxxxxxxx0000000000xx-jwt=<jwt_token>; path=/; expires=Fri, 23 Apr 2021 04:15:19 GMT; domain=.somedomain.com; samesite=none; secure';

const myCookie = unparsedCookie.split(';')[0];
const [name, value] = myCookie.split('=');

console.log(name);
console.log(value);

但请记住,Set-cookie 可能被编码为 URI 组件。

A <cookie-value> can optionally be wrapped in double quotes and include any US-ASCII characters excluding control characters, Whitespace, double quotes, comma, semicolon, and backslash. Encoding: Many implementations perform URL encoding on cookie values, however it is not required per the RFC specification. It does help satisfying the requirements about which characters are allowed for though.

MDN

因此,您可能需要使用 decodeURIComponent() 对其进行解码。

但是,由于您的案例是 JWT 令牌,因此您不必担心。 JWT 应该生成为 base64url,这对 url.

友好