Setting Cookies with CORS requests

后端 未结 1 525
北荒
北荒 2020-12-17 18:38

I\'ve been trying to tackle this problem for a few days. Setting cookies on CORS requests. I\'ve seen conflicting articles and answers, some saying that as long as the XHR r

1条回答
  •  有刺的猬
    2020-12-17 18:43

    What wasn't immediately obvious is that cookies set by the server, at least in CORS requests, and possibly (probably) in all requests are limited to the same domain as the server.

    index.js (Node.js Server)

    const http = require('http');
    const fs = require('fs');
    
    // Pretty colors
    
    const colors = {
      purple: '\033[95m',
      orange: '\033[93m',
      blue: '\033[97m',
      underline: '\033[4m',
      bold: '\033[1m',
      reset: '\033[0m'
    }
    
    const server = http.createServer(function (req, res) {
    
      //Console logs to verify what's getting hit. 
    
      console.log(colors.purple + colors.underline + 'Hit it!' + colors.reset);
      console.log(colors.orange + colors.bold + 'url:' + colors.reset, req.url);
    
      if (/\/cookie/.test(req.url)) {
        console.log(colors.blue + 'We need to cook(ie) Jesse\n' + colors.reset);
        // Generate a random string in a rather convoluted way.
        var randomStr = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(36) + 
        Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(36) + 
        Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(36);
        randomStr = new Buffer(randomStr.toString(), 'binary').toString('base64');
        // All .dev domains pointed to localhost via dnsmasq, though a hosts file
        // Update should also do the trick.
        res.writeHead(200, {
          'Set-Cookie': 'ajaxTestCookie=cookie' + randomStr + '; domain=.example.dev; HttpOnly',
          'Access-Control-Allow-Origin': 'http://example.dev:3999',
          'Access-Control-Allow-Credentials': 'true',
          'Access-Control-Allow-Methods': 'GET, POST',
          'Access-Control-Allow-Headers': 'Content-Type, Set-Cookie, *'
        });
        return res.end('OK!');
      }
      console.log(colors.blue + 'We\'re having fun at the HTML!\n' + colors.reset);
      // Send out html file. 
      fs.readFile('./cookies.html', function (err, data) {
        if (err) {
          res.writeHead(500);
          return res.end('Failure to launch!');
        }
        res.end(data.toString());
      });
    });
    
    server.listen(3999); // api.example.dev:3999, for example
    

    cookies.html

    
    
    
      Cookie Test
    
    
    
      
      
    
    

    0 讨论(0)
提交回复
热议问题