0

I've already checked out these two SO questions: Can I use localhost as the domain when setting an HTTP cookie? Setting a cookie from a remote domain for local development

But I don't want to edit my HOSTS file and setting a wildcard domain doesn't help me.

I've used node.js, but it should be programming language agnostic...

So my problem is the following:

I wanna work on my Angular frontend on https://localhost:4200 (and possibly http://localhost:4200) and reach my backend by getting access to it. Obviously I have to implement CORS rules for that, hence I've implemented the following CORS rules in the Node.js backend:

const allowedOrigins = environment.header;
  const origin = req.headers.origin;
  if (allowedOrigins.includes(origin)) {
       res.setHeader('Access-Control-Allow-Origin', origin);
  }

where allowedOrigins is an array that contains the following:

environment.header = ['https://localhost:4200', 'http://localhost:4200', 'http://test.example.org', 'https://test.example.org'];

The problem at hand is that when I go to work on my Angular frontend locally it does not send the cookie to the backend for some reason (maybe this kind of connection is simply not allowed by some RFC???), hence my JWT checking mechanism throws 403 Forbidden after logging in instantly.

My JWT check function looks like this:

if (req.headers.origin === 'https://localhost:4200' || 'http://localhost:4200')
        orig = 'localhost';
        else 
        orig = req.headers.origin;
        res.cookie(
            'access_token', 'Bearer ' + token, {
            //domain: 'localhost',
            domain: orig,
            path: '/',
            expires: new Date(Date.now() + 900000), // cookie will be removed after 15 mins
            httpOnly: true // in production also add secure: true
        })

I need to do this to work on my Angular frontend locally and the backend has a connection to another server, which works only locally for now...

withCredentials is of course true (so the JWT cookie is being sent with), so that's not the problem in my codebase.

UPDATE

Ok so I've figured out that req.headers.origin is usually undefined..

UPDATE 2

Changed req.headers.origin to req.headers.host, but still it doesn't work

Munchkin
  • 857
  • 5
  • 24
  • 51

1 Answers1

0

I needed to add the following properties to the res.cookie for it to work: sameSite: 'none', secure: true

Then I enabled third-party cookies in Incognito mode and it worked for me.

Case closed.

Munchkin
  • 857
  • 5
  • 24
  • 51