-2

i set secret key by Express: res.cookie('name','value', {signed:true}); and want to parse the signed cookie in client javascript, such as document.cookie or $.cookie(), but i can't find out where there is any API for that. do anyone know about it?

Sunny Sun
  • 65
  • 5
  • 13
  • 1
    What's the problem, exactly? Does your cookie not appear in the list from `document.cookie`? – msanford Oct 11 '17 at 14:14
  • https://stackoverflow.com/questions/5639346/what-is-the-shortest-function-for-reading-a-cookie-by-name-in-javascript – epascarello Oct 11 '17 at 14:17
  • it appears but it is encrypted. this is what i got by document.cookie.name or $.cookie('name):`s:0.vunrLqeIl9xNAJFmibUmCeWeI3vDS9m/mbnkAZiVubU`. as you know, we can parser cookie in server side. such as `req.signedCookies`, but in client side, there is no such API to do that. – Sunny Sun Oct 11 '17 at 14:20
  • @epascarello the method you gave is to just read cookie, and i need to parse the signed cookie in javascript client side, provided i know the secret key – Sunny Sun Oct 11 '17 at 14:25

1 Answers1

2

Given a cookie value of s:0.vunrLqeIl9xNAJFmibUmCeWeI3vDS9m/mbnkAZiV‌​ubU, its value will be 0. The prefix s: signifies that its a signed cookie, and the suffix .vunr...ubU is the actual signature.

So to extract the value, you can use something like this:

let value = $.cookie('name').match(/^s:(.*)\..*$/)[1];

Or, if you're using a bundler like Webpack or Browserify, you may be able to use the actual module that it used to create and verify signed cookies in Express: cookie-signature.

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • thanks a lot. i thought there was off-shelf API in client to use directly, but it seems still has to use webpack to bundle module into front end. – Sunny Sun Oct 11 '17 at 15:34