0

When logging in to my Yii2 + angularjs page, I create cookie with user data:

$jwt = JWT::encode(array(1,2,3), 'myKey123')
setcookie('myData', $jwt, time() + 3600);

I want to access it in my nodejs + express app - before processing request I have to check, if user didn't change 'myData' cookie. This is how I do it now:

app.use(cookieParser());

app.get('/*', function (req, res, next) {
    if(req.cookies.myData) {
        jwt.verify(req.cookies.myData, 'myKey123', function(err, decoded) {
            if(err)
                res.sendStatus(403);
            else
                return next();
        });
    } else {
        res.sendStatus(403);
    }
});

If after I logging in I call expressjs route directly in browser, app sees cookie.

Problem: If route is called by making $http.get() request, expressjs app doesn't see any cookies.

Yii2 and expressjs runs on the same IP, but on different ports, but I've read, that different ports shouldn't be the reason, should it? I've played around with setting different cookie parameters, but nothing seems to help. I'd appreciate any help or hints I could get, thank you!

Lina
  • 15
  • 9
  • See [Are HTTP cookies port specific?](http://stackoverflow.com/questions/1612177/are-http-cookies-port-specific). – jfriend00 May 09 '17 at 17:42
  • Yeah, I've read this before creating my question, that's where I learned, that different ports can use same cookies. So in theory, my code should work, right? But it doesn't. Do I maybe have to add some extra parameters or settings to $http.get() maybe, since I can't get any cookies when sending requests to express app? – Lina May 09 '17 at 19:48
  • I'd suggest you log all cookies present on both client and server. There are other reasons you can lose cookies (domain mismatch, path mismatch, expiration, improper setting of the cookie, etc...). It does appear that a different port does not prevent cookies from being sent unless the cookie was specifically set for only one port, but there are lots of other reason it could happen. You will have to do some debugging to learn more. Hard for us to guess based on the limited code we can see. – jfriend00 May 09 '17 at 20:05

1 Answers1

0

So I know what's wrong now - in my $http.get() requests I simply didn't set withCredentials: true. When request was "made" directly in browser, cookies were passed by default, but when doing it via $http.get(), I had to set extra argument, for example:

$http.get(myService('myRoute'), {
    params: {
        param1: 1,
        param2: 2
    },
    withCredentials: true
}).then(function(response) {
    $scope.returnedData = response.data;
});

Source: AngularJs documentation for $http requests

withCredentials - {boolean} - whether to set the withCredentials flag on the XHR object. See requests with credentials for more information.

Lina
  • 15
  • 9