Error cookieparser secret required for signed cookies

I am working on express/node.js and trying to understand cookies of expressjs and I'm setting cookie like this: var express = require('express'); var app = express(); var cookieParser = require('

If you set signed:true option, you have to set secret key as string as parameter for cookieParser() as follows:

var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
//Set secret key
app.use(cookieParser('your random secret string here'));

//Set/Write Cookies
app.get('/',function(req, res){
    res.cookie('cookie1', 'This is my first cookie', {signed:true, maxAge: 1000*60*60*24*7, httpOnly: true});
    res.end('Cookie has been set');
});

Otherwise just leave it blank as follows:

app.use(cookieParser());

For accessing the signed cookie value, you can try as follows:

//Read Cookies
app.get('/readCookies',function(req, res){
    res.send(req.signedCookies['cookie1']);
    //OR, req.signedCookies.cookie1
});

Or, you can check cookies from your browser console as follows if you don’t set httpOnly: true option:

document.cookie

For destroying cookies try as follows:

//Remove Cookies
app.get('/removeCookies',function(req, res){
    res.clearCookie('cookie1');
    res.send("Cookie has been cleared");
});

For more details please check res.cookie(name, value [, options])

Я работаю над express / node.js и пытаюсь понять файлы cookie expressjs, и я устанавливаю файл cookie следующим образом:

var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
app.use(cookieParser());

app.get('/', function(req, res){
    res.cookie('cookie1', 'This is my first cooke', {maxAge: 1000*60*60*24*7, httpOnly: true});
    res.end('Cookie has been set');
});

И доступ к файлам cookie следующим образом:

app.get('/readCookies',function(req, res){
    res.send(req.cookies.cookie1);
});

Но проблема заключается в опции signed: true, когда при включении этого параметра для кодирования значения cookie во время установки cookie я получаю следующую ошибку:

Error: cookieParser("secret") required for signed cookies

Пожалуйста, помогите мне и заранее спасибо

2 ответа

Лучший ответ

Ошибка объясняет, что вам нужно сделать, чтобы иметь возможность отправлять подписанные файлы cookie:

Ошибка: для подписанных файлов cookie требуется cookieParser («секрет»)

В Экспресс-документации говорится:

При использовании промежуточного программного обеспечения cookie-parser этот метод также поддерживает подписанные файлы cookie. Просто включите параметр signed, установленный на true. Затем res.cookie() будет использовать секрет, переданный cookieParser(secret), чтобы подписать значение.

В документации cookie-parser говорится:

cookieParser (секрет, параметры) :

  • secret строка или массив, используемый для подписи файлов cookie. Это необязательно и, если не указано, не будет анализировать подписанные файлы cookie. Если указана строка, она используется как секрет.

Итак, все вместе:

  • установить промежуточное ПО cookie-parser:

    npm install cookie-parser
    
  • добавьте его в приложение Express:

    const cookieParser = require('cookie-parser');
    
    ...
    app.use(cookieParser('MY SECRET'));
    
  • заставить его подписывать куки:

    res.cookie('cookie1', 'This is my first cookie', { signed : true });
    
  • и прочтите значение cookie обратно:

    res.send(req.signedCookies.cookie1);
    


10

robertklep
11 Ноя 2018 в 14:53

Если вы устанавливаете опцию signed:true, вам необходимо установить секретный ключ как строку в качестве параметра для cookieParser() следующим образом:

var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
//Set secret key
app.use(cookieParser('your random secret string here'));

//Set/Write Cookies
app.get('/',function(req, res){
    res.cookie('cookie1', 'This is my first cookie', {signed:true, maxAge: 1000*60*60*24*7, httpOnly: true});
    res.end('Cookie has been set');
});

В противном случае просто оставьте поле пустым, как показано ниже:

app.use(cookieParser());

Чтобы получить доступ к значению подписанного файла cookie, вы можете попробовать следующее:

//Read Cookies
app.get('/readCookies',function(req, res){
    res.send(req.signedCookies['cookie1']);
    //OR, req.signedCookies.cookie1
});

Или вы можете проверить файлы cookie из консоли браузера следующим образом, если вы не установили параметр httpOnly: true:

document.cookie

Для уничтожения файлов cookie попробуйте следующее:

//Remove Cookies
app.get('/removeCookies',function(req, res){
    res.clearCookie('cookie1');
    res.send("Cookie has been cleared");
});

Для получения дополнительной информации проверьте res.cookie (имя, значение [, параметры])

@MattMorgis

I have cookie-parser configured in my app.js file like so:

app.use(cookieParser(process.env.SECRET));

I am also using web-sessions for authentication with the same secret:

var webSession = {
    name: 'sid',
    secret: process.env.SECRET,
    resave: false,
    saveUninitialized: false, // don't create the session until something is stored.
    unset: 'keep',
    rolling: true,
    cookie: {maxAge: 3600000} // one hour
};

I am setting a cookie as follows:

var cookie = req.signedCookies.cart;
if (cookie === undefined) {
    // no cart: set a new cookie
    var item = {
        id: req.body.id,
        quantity: 1
    };
    var cart = [item];
    res.cookie('cart', cart, {signed:true, maxAge: 604800000, httpOnly: true}); //maxAge=1 week.
    console.log('cookie created successfully');
    res.send('cookie created');
} else {
    // cart was already created
    console.log('cookie exists', cookie);
    // TODO: check if item is already in cart.
    cookie = cookieParser.signedCookie('cart', process.env.SECRET);
    console.log(cookie);
}

Output:

cookie created successfully
cookie exists [ { id: '15', quantity: 1 } ]
cart

I can read the signed cookie using the basic req.signedCookies, but when I try with cookieParser.signedCookie, it simply returns the value I pass to the function back to me. Is this is an error with me signing the cookie and configuring my secret’s or a bug in cookie-parser?

@MattMorgis

Also — forgot to note that the cookie does appear in my browser:

cart:s%3Aj%3A%5B%7B%22id%22%3A%2215%22%2C%22quantity%22%3A1%7D%5D.V41NgThciSMu7cdnDY%2FN3BEfchst9pqL7FEFrxKTNHw

@dougwilson

Hi @MattMorgis, I’m trying to read the information here, but I feel like it is just a thought stream, and I really cannot tell what the question is.

I can say that the cookieParser.signedCookie function is documented in the README: https://github.com/expressjs/cookie-parser#cookieparsersignedcookiestr-secret

Does the documentation help at all with what you are trying to do? If not, what can we change in the documentation to clarify? If you are getting the same value back that you gave to the function, then that means that value you provided was not signed (or the signature was invalid), according to the documentation.

The code you put in the «I am setting a cookie as follows» section does not use the cookieParser.signedCookie function in any useful way, since the value you are passing in as the first argument came from req.signedCookies.cart, the value would have already been un-signed, and thus there is no longer anything to unsign, so the function just returns the original value.

NPM Version
NPM Downloads
Build Status
Test Coverage

Parse Cookie header and populate req.cookies with an object keyed by the
cookie names. Optionally you may enable signed cookie support by passing a
secret string, which assigns req.secret so it may be used by other
middleware.

Installation

$ npm install cookie-parser

API

var cookieParser = require('cookie-parser')

cookieParser(secret, options)

Create a new cookie parser middleware function using the given secret and
options.

  • secret a string or array used for signing cookies. This is optional and if
    not specified, will not parse signed cookies. If a string is provided, this
    is used as the secret. If an array is provided, an attempt will be made to
    unsign the cookie with each secret in order.
  • options an object that is passed to cookie.parse as the second option. See
    cookie for more information.

    • decode a function to decode the value of the cookie

The middleware will parse the Cookie header on the request and expose the
cookie data as the property req.cookies and, if a secret was provided, as
the property req.signedCookies. These properties are name value pairs of the
cookie name to cookie value.

When secret is provided, this module will unsign and validate any signed cookie
values and move those name value pairs from req.cookies into req.signedCookies.
A signed cookie is a cookie that has a value prefixed with s:. Signed cookies
that fail signature validation will have the value false instead of the tampered
value.

In addition, this module supports special “JSON cookies”. These are cookie where
the value is prefixed with j:. When these values are encountered, the value will
be exposed as the result of JSON.parse. If parsing fails, the original value will
remain.

cookieParser.JSONCookie(str)

Parse a cookie value as a JSON cookie. This will return the parsed JSON value
if it was a JSON cookie, otherwise, it will return the passed value.

cookieParser.JSONCookies(cookies)

Given an object, this will iterate over the keys and call JSONCookie on each
value, replacing the original value with the parsed value. This returns the
same object that was passed in.

cookieParser.signedCookie(str, secret)

Parse a cookie value as a signed cookie. This will return the parsed unsigned
value if it was a signed cookie and the signature was valid. If the value was
not signed, the original value is returned. If the value was signed but the
signature could not be validated, false is returned.

The secret argument can be an array or string. If a string is provided, this
is used as the secret. If an array is provided, an attempt will be made to
unsign the cookie with each secret in order.

cookieParser.signedCookies(cookies, secret)

Given an object, this will iterate over the keys and check if any value is a
signed cookie. If it is a signed cookie and the signature is valid, the key
will be deleted from the object and added to the new object that is returned.

The secret argument can be an array or string. If a string is provided, this
is used as the secret. If an array is provided, an attempt will be made to
unsign the cookie with each secret in order.

Example

var express = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

app.get('/', function (req, res) {
  // Cookies that have not been signed
  console.log('Cookies: ', req.cookies)

  // Cookies that have been signed
  console.log('Signed Cookies: ', req.signedCookies)
})

app.listen(8080)

// curl command that sends an HTTP request with two cookies
// curl http://127.0.0.1:8080 --cookie "Cho=Kim;Greet=Hello"

License

MIT

A cookie is a piece of data that is sent to the client-side with a request and is stored on the client-side itself by the Web Browser the user is currently using. With the help of cookies –

  • It is easy for websites to remember the user’s information
  • It is easy to capture the user’s browsing history
  • It is also useful in storing the user’s sessions

The session makes requests to all the servers using a secret Id. The information is stored on the server that is linked to this secret ID.
To make use of cookies in our application, cookie-parser middleware is used. To install it, write the following command –

npm install cookie-parser@latest --save

Also, to install express middleware write the following command –

npm install express@latest --save

These commands will install the latest versions of cookie-parser and express.
Cookie-parser middleware is used to parse the cookies that are attached to the request made by the client to the server. Therefore, to use cookie-parser, we will write the following lines of code in our JavaScript file –

const cookieParser = require('cookie-parser');

const express = require('express')

const app = express();

app.use(cookieParser());

Let’s look at an example of how to setup a new cookie. Create a new file named “index.js”. For setting up and assigning a name to a cookie, follow the code –

const express = require('express');

const cookieParser = require('cookie-parser');

const app = express();

app.get('/', (req, res) => {

   res.cookie('name', 'GeeksForGeeks').send('Cookie-Parser');

});

app.listen(3000, (err) => {

    if(err){ console.log(err) } 

    else { console.log('Success!!') }

});

Here, we sent the cookie to the new route and set the name of the cookie as ‘GeeksForGeeks’. In the last block of code, our server is listening to the port 3000 with a callback function. If there will be an error then the callback function will return the error else it will return “Success”.
Now, run the following code with the command –

node index.js

To check if the cookie is set or not, just go to this link after successfully setting up the server. Open the console and write the command as –

document.cookie

You will get the output as –

"name=GeeksForGeeks"

Also, the cookie-parser middleware populates the req.cookies with name that is sent to the server. Here, in our case, we can add the following line of code in our route –

console.log(req.cookies)

The output of the above line will be –

{ name: 'GeeksForGeeks' }

Methods for cookie-parser

  • cookieParser(secret, options)
  • – This middleware takes two parameters. First one will be the secret Id and other will the options. The secret Id can be a string or an array of strings. If the secret parameter is not provided then it will take the cookie as unsigned cookie. Therefore, it is optional to provide the secret ID. The second parameter will be an object specifying what actions to be taken with the cookies. For example, decode is a function to decode the value of the cookie.

  • cookieParser.JSONCookie(str)
  • – This method will parse the value of the cookie as a JSON cookie. It will return the parsed JSON value if the cookie provided is a JSON cookie. If not a JSON cookie, it will return the passed value itself.

  • cookieParser.JSONCookies(cookies)
  • – Provided an object with its Id attached. This method will iterate over the Object Id’s provided and will call the “JSONCookie” on each value. It will replace the original value with the parsed value. This will return the same object that was passed in.

  • cookieParser.signedCookie(string, secret)
  • – This method parses the cookie as a signed cookie. If the cookie is a signed cookie and signature can be validated, then it will return the parsed unsigned value. If the cookie is unsigned, then the original value is returned. If the cookie is signed but the signature cannot be validated, then false is returned.
    Now, our second argument secretcan be a string or an array of strings. If it is a string, then it will be used as a secret. If it is an array, then iteration over each element of the array will be done and the cookie will be unsigned using each secret.

  • cookieParser.signedCookies(cookies, secret)
  • – This method will perform the iteration over each ID and check if any ID is a signed cookie. If it is signed and the signature can be validated, then the ID will be deleted from the object will it will be added to the new returning object.

Depending on the type of the cookie sent from the client, these methods will automatically be called.

Implementation of Signed and Unsigned Cookie

Unsigned Cookie

const express = require('express');

const cookieParser = require('cookie-parser');

const app = express();

app.get('/', (req, res) => {

   res.cookie('name', 'GeeksForGeeks').send();

   console.log(req.cookies);

});

app.listen(3000, (err) => {

    if(err){ console.log(err) } 

    else { console.log('Success!!') }

});

The output for the above code will be –

"name=GeeksForGeeks"
Signed Cookie

var express = require('express')

var cookieParser = require('cookie-parser')

var app = express()

app.use(cookieParser('GFG'))

app.get('/', function (req, res) {

  res.cookie('name', 'GeeksForGeeks', { signed: true }).send();

  console.log(req.signedCookies)

})

app.listen(3000, (err) => {

  if(err) { console.log(err) }

  else { console.log('Success') }

})

Here, In the 4th line – “GFG” is provided as a secret value to the cookie.
In the 7th line – the name for the cookie is set to “GeeksForGeeks” and the object signed is set to true.
The output for the above code will be –

{ name: 'GeeksForGeeks' }

Файл cookie — это фрагмент данных, который отправляется клиентской стороне с запросом и хранится на самой стороне клиента веб-браузером, который в данный момент использует пользователь. С помощью куки —

  • Веб-сайтам легко запоминать информацию о пользователе.
  • Легко фиксировать историю просмотров пользователя
  • Это также полезно для хранения сеансов пользователя.

Сеанс делает запросы ко всем серверам, используя секретный идентификатор. Информация хранится на сервере, который связан с этим секретным идентификатором.
Чтобы использовать файлы cookie в нашем приложении, используется промежуточное ПО для парсера файлов cookie. Чтобы установить его, напишите следующую команду —

 npm install cookie-parser @ latest --save

Кроме того, чтобы установить промежуточное ПО промежуточного уровня, напишите следующую команду —

 npm install express @ latest --save

Эти команды установят последние версии cookie-parser и express.
Промежуточное ПО для парсера файлов cookie используется для анализа файлов cookie, прикрепленных к запросу, сделанному клиентом серверу. Поэтому, чтобы использовать cookie-parser, мы напишем следующие строки кода в нашем файле JavaScript:

const cookieParser = require( 'cookie-parser' );

const express = require( 'express' )

const app = express();

app.use(cookieParser());

Давайте посмотрим на пример того, как настроить новый файл cookie. Создайте новый файл с именем «index.js». Для настройки и присвоения имени файлу cookie следуйте коду —

Здесь мы отправили файл cookie на новый маршрут и установили имя файла cookie как «GeeksForGeeks». В последнем блоке кода наш сервер прослушивает порт 3000 с помощью функции обратного вызова. Если произойдет ошибка, функция обратного вызова вернет ошибку, иначе она вернет «Успех».
Теперь запустите следующий код с командой —

 узел index.js

Чтобы проверить, установлен ли файл cookie, просто перейдите по этой ссылке после успешной настройки сервера. Откройте консоль и напишите команду как —

 document.cookie

Вы получите результат как —

 "name = GeeksForGeeks"

Кроме того, промежуточное программное обеспечение парсера файлов cookie заполняет файлы req.cookies именем, которое отправляется на сервер. Здесь, в нашем случае, мы можем добавить следующую строку кода в наш маршрут —

 console.log (req.cookies)

Результатом вышеуказанной строки будет —

 {name: 'GeeksForGeeks'}

Методы для cookie-парсера

  • cookieParser (секрет, параметры)

    — Это промежуточное ПО принимает два параметра. Первым будет секретный идентификатор, а вторым — параметры. Секретный идентификатор может быть строкой или массивом строк. Если секретный параметр не указан, cookie будет восприниматься как неподписанный. Следовательно, указывать секретный идентификатор необязательно. Вторым параметром будет объект, определяющий, какие действия следует выполнять с файлами cookie. Например, decode — это функция для декодирования значения cookie.

  • cookieParser.JSONCookie (str)

    — Этот метод анализирует значение файла cookie как файла cookie JSON. Он вернет проанализированное значение JSON, если предоставленный файл cookie является файлом cookie JSON. Если это не файл cookie JSON, он сам вернет переданное значение.

  • cookieParser.JSONCookies (файлы cookie)

    — Предоставлен объект с прикрепленным идентификатором. Этот метод будет перебирать предоставленный идентификатор объекта и вызывать «JSONCookie» для каждого значения. Он заменит исходное значение проанализированным значением. Это вернет тот же объект, который был передан.

  • cookieParser.signedCookie (строка, секрет)

    — Этот метод анализирует файл cookie как подписанный. Если файл cookie является подписанным файлом cookie и подпись может быть проверена, он вернет проанализированное беззнаковое значение. Если cookie не подписан, возвращается исходное значение. Если файл cookie подписан, но подпись не может быть проверена, возвращается false.
    Теперь наш второй секрет аргумента может быть строкой или массивом строк. Если это строка, то она будет использоваться как секрет. Если это массив, то будет выполняться итерация по каждому элементу массива, и cookie будет беззнаковым с использованием каждого секрета.

  • cookieParser.signedCookies (куки, секрет)

    — Этот метод будет выполнять итерацию по каждому идентификатору и проверять, является ли какой-либо идентификатор подписанным файлом cookie. Если он подписан и подпись может быть проверена, то идентификатор будет удален из объекта, если он будет добавлен к новому возвращаемому объекту.

В зависимости от типа файла cookie, отправленного клиентом, эти методы будут вызываться автоматически.

Реализация подписанных и неподписанных файлов cookie

Неподписанный файл cookie

const express = require( 'express' );

const cookieParser = require( 'cookie-parser' );

const app = express();

app.get( '/' , (req, res) => {

res.cookie( 'name' , 'GeeksForGeeks' ).send();

console.log(req.cookies);

});

app.listen(3000, (err) => {

if (err){ console.log(err) }

else { console.log( 'Success!!' ) }

});

Вывод для приведенного выше кода будет —

 "name = GeeksForGeeks"
Подписанный файл cookie

var express = require( 'express' )

var cookieParser = require( 'cookie-parser' )

var app = express()

app.use(cookieParser( 'GFG' ))

app.get( '/' , function (req, res) {

res.cookie( 'name' , 'GeeksForGeeks' , { signed: true }).send();

console.log(req.signedCookies)

})

app.listen(3000, (err) => {

if (err) { console.log(err) }

else { console.log( 'Success' ) }

})

Здесь, в 4-й строке — «GFG» предоставляется как секретное значение для файла cookie.
В 7-й строке — имя файла cookie установлено на «GeeksForGeeks», а подписанный объект имеет значение true.
Вывод для приведенного выше кода будет —

 {name: 'GeeksForGeeks'}

я новичок в работе с nodejs, и я просто пытаюсь запустить сервер, который уже работает с моими товарищами по команде. Я на Mac и уже установил все необходимые модули с помощью «npm install». Теперь похоже проблема с модулем «cookie-подпись», который уже включен в «экспресс»-модуль. Я пытаюсь запустить программу и не получаю никаких ошибок, но когда я пытаюсь открыть страницу на локальном хосте: 3000, я получаю следующую ошибку:

/Users/kevinglaap/Sites/Uni/git/node_server/node_modules/express/node_modules/cookie-signature/index.js:19
  if ('string' != typeof secret) throw new TypeError('secret required');
                                       ^
TypeError: secret required
    at Object.exports.sign (/Users/kevinglaap/Sites/Uni/git/node_server/node_modules/express/node_modules/cookie-signature/index.js:19:40)
    at ServerResponse.end (/Users/kevinglaap/Sites/Uni/git/node_server/node_modules/express/node_modules/connect/lib/middleware/session.js:267:34)
    at ServerResponse.EventEmitter.emit (events.js:93:17)
    at ServerResponse.res.writeHead (/Users/kevinglaap/Sites/Uni/git/node_server/node_modules/express/node_modules/connect/lib/patch.js:73:36)
    at ServerResponse._implicitHeader (http.js:932:8)
    at ServerResponse.OutgoingMessage.end (http.js:767:10)
    at res.end (/Users/kevinglaap/Sites/Uni/git/node_server/node_modules/express/node_modules/connect/lib/middleware/session.js:282:13)
    at /Users/kevinglaap/Sites/Uni/git/node_server/node_modules/express/node_modules/connect/lib/middleware/session/memory.js:73:11
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

Модуль никогда не используется в ресурсах сервера. Я уже проверил использование «знаковой» функции, потому что ошибка является извлеченной ошибкой, которая сигнализирует о том, что ресурсы могут делать что-то не так, но она используется только экспрессом или другими модулями в экспрессе. Я искал в Интернете уже несколько дней и еще не нашел решения. Что мне не хватает? Заранее спасибо за помощь.

4 ответы

При настройке вашего экспресс-экземпляра вам нужно следующее:

app.use(express.cookieParser('your secret option here'));
app.use(express.session());

Убедитесь, что ваш cookieParser (с вашей секретной строкой) находится перед express.session()

ответ дан 20 мая ’22, 19:05

с обновленной экспресс-версией:

var app = express();
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));

ответ дан 15 дек ’17, 20:12

Следует добавить секрет при создании экземпляра экспресс-сессии в промежуточном программном обеспечении.

Всегда полезно иметь файл .env для хранения всех секретов, а не просто для добавления строки.

В .env:

secret='my_secret'

В server.js:

app.use(cookieParser())
app.use(session({
  resave:true,
  saveUninitialized:true,
  secret:process.env.secret,
  cookie:{maxAge:3600000*24}
}))

ответ дан 04 мая ’21, 08:05

app.use(session({
    secret: process.env.SECRET,
    reserve: true,
    saveUninitialized: true,
    cookie:{secure: false}
})
)
    .env
PORT=6000
CONNECTION_STRING=mongodb://localhost:27017//bookingApp
SECRET=[thinkbeforactingalwas]
MODE_ENV=development

Создан 15 фев.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

node.js
express

or задайте свой вопрос.

Понравилась статья? Поделить с друзьями:
  • Error converting value to type system
  • Error converting to execution character set invalid or incomplete multibyte or wide character
  • Error converting to execution character set illegal byte sequence
  • Error converting one or more entries
  • Error converting data type varchar to float перевод