Passport.js express google oauth 502 Bad Gateway on nginx

Issue

I am trying to implement a simple Google OAuth for my Express.js app using passport.js following this guide (just replace facebook with google) https://github.com/passport/express-4.x-facebook-example/blob/master/server.js

When I try it locally, things seem to be working well. When I deploy it to my Ubuntu production server, I get a 502 Bad Gateway error during the redirect callback from Google to the /login/google/return endpoint.

app.get('/login/google/return', 
  passport.authenticate('google', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

If I comment out the the line passport.authenticate('google', {..}), then the error goes away. Upon inspecting nginx error log, I see this error

upstream sent too big header while reading response header from upstream

Here’s the server configuration block for nginx:

location /auth/ {
   proxy_pass http://0.0.0.0:3000/;
}

Which means that I would log in to google by going to https://example.com/auth/login/google, being redirected to https://example.com/auth/login/google/return?code=4/adasfdafdsfd#, and then the 502 error happens.

I have tried setting up a similar nginx environment on my OS X development machine, but the problem does not occur there.

I have also tried to add the following to the nginx block configuration, but that doesn’t seem to help either

proxy_buffers 8 16k;

I am at my wit’s end as to how to debug/ solve this problem. Anyone’s suggestion would be greatly appreciated. Here’s the link to my project so far https://github.com/tnguyen14/auth/blob/master/index.js

Solution

So I was close. proxy_buffers 8 16k; was not sufficient. Adding both of the following lines to nginx fixed it:

proxy_buffers 8 16k;
proxy_buffer_size 32k;

UPDATE: turns out, the reason why it complained about the header size is because I did not serialize the user profile sufficiently, so the object is too big for the cookie. Since I am using cookie-session, all of that data is stuffed into the cookie, making it too big.

Trimming down the things that would be serialize by passport session solves this problem without the added nginx config.

Answered By – Tri Nguyen

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published