Feature Request - Expose cookies as variable
I need to use a cookie value set in a previous request in the next request to implement the csrf double submit pattern.
Right now I have to use a script like:
{{
const { store } = require("httpyac");
const cookies = store.userSessionStore.userSessions.filter(s => s.type === 'Cookie').map(c => c.cookie);
const sorted = cookies.sort((a, b) => new Date(b.creation) - new Date(a.creation)) // sort by creation date in descending order
const cookie = sorted.find(c => c.domain == 'localhost' && c.key == 'csrf_') // find the csrf cookie for localhost
exports.csrfToken = cookie?.value || '';
}}
I wish I could do something like:
/pets
X-Csrf-Token: {{cookie.csrf}}
Since http-yac already filters the relevant cookies to send out with a request (based on domain, path, expiry etc), it would be helpful if they are available as a variable.
See also: https://github.com/Huachao/vscode-restclient/issues/316
I also posted a question on the Discord: https://discord.com/channels/1246356025724895242/1349292504079667274
@aphilas A simpler API for handling cookies would be possible. Unfortunately, your suggestion with cookie.crsf is not enough, as the cookie is only similar to that and not exact. However, it could probably be solved using a method. Maybe something like
/pets
X-Csrf-Token: {{$cookies.find(t => t.key.startsWith("crsf_")}}
as the cookie is only similar to that and not exact
What does this mean?
For a given request (domain, path, etc...), there are zero or more active cookies matching a given name. We may want to have a configurable sort order, and pick the first one. RFC 6265 [^notread] defines some order but proposes not depending on it.
X-Csrf-Token: {{$cookies.find(t => t.key.startsWith("crsf_")}}
I am not intimate with httpyac's scripting convention so this may be moot: In the global scope, the $cookie variable above makes sense. In the request scope, we have more attributes to filter out unwanted cookies.
[^notread]: I haven't read it, yet