从API w / Express http-proxy存储令牌

我正在设置一个通用的React应用程序,并以此项目为基础。 我成功地代理请求(使用http代理 )到我的Laravel后端。 不过,我是Nodejs的新手,我不知道如何从代理服务器安全地存储JWT到客户端的最佳方法。

我最初的想法是将标记存储到localStorage,但问题是快速服务器将无法访问它。 所以我的下一个猜测是将其存储为一个cookie,但我不知道如何将其存储在客户端,或将其作为所有传出请求的头部(另外,我可能需要某种csrf中间件)。

那么,如何操纵我的api服务器的响应,将一个令牌放置在客户端设置的cookie中,然后将其用作所有api请求的载体令牌?

// server.js const targetUrl = 'http://' + config.apiHost + ':' + config.apiPort; const app = new Express(); const server = new http.Server(app); const proxy = httpProxy.createProxyServer({ target: targetUrl, changeOrigin: true }); // Proxy to Auth endpoint app.use('/auth', (req, res) => { // on a successful login, i want to store the token as a cookie proxy.web(req, res, {target: targetUrl}); }); // Proxy to api endpoint app.use('/api', (req, res) => { // use the token in the cookie, and add it as a authorization header in the response proxy.web(req, res, {target: targetUrl}); }); 

鉴于laravel中auth端点的响应如下所示:

 { "token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ" } 

这段代码将做你想做的事情:

 // server.js const targetUrl = 'http://' + config.apiHost + ':' + config.apiPort; const Express = require('express'); const http = require('http'); const httpProxy = require('http-proxy'); const app = new Express(); const server = new http.Server(app); const Cookies = require( "cookies" ) const proxy = httpProxy.createProxyServer({ target: targetUrl, changeOrigin: true }); // Proxy to Auth endpoint app.use('/auth', (req, res) => { // on a successful login, i want to store the token as a cookie // this is done in the proxyRes proxy.web(req, res, {target: targetUrl}); }); // Proxy to api endpoint app.use('/api', (req, res) => { // use the token in the cookie, and add it as a authorization header in the response var cookies = new Cookies( req, res ) req.headers.authorization = "JWT " + cookies.get('jwt-token'); proxy.web(req, res, {target: targetUrl}); }); proxy.on('proxyRes', function(proxyRes, req, res) { if (req.originalUrl === '/auth') { var cookies = new Cookies( req, res ) var body = ''; var _write = res.write; var _end = res.end; var _writeHead = res.writeHead; var sendHeader = false; res.writeHead = function () { if (sendHeader) { _writeHead.apply( this, arguments ); } } res.write = function (data) { body += data; } res.end = function () { sendHeader = true; var parsed = JSON.parse(body); cookies.set('jwt-token', parsed.token); _write.apply(this, [ body ]); _end.apply(this, arguments); } } });