简体   繁体   中英

passport req.isAuthenticated always return false when using angular $http request

I am using passportjs for my user authentication.

By using postman , I can successfully login and req.isAuthenticated always returns me true in the subsequence requests after login.

By using angular $http , However, login works ok but the req.isAuthenticated always returns me false in the subsequence request. My angular app(localhost:3000) and the node app(heroku) are at different domain. My thoughts was it may relate to either CORS or session cookie since I do not see any cookies in my browser.

What I have done

  1. I tried to set the request header to allow CORS.
  2. I also tried to set Access-Control-Allow-Credentials at both angular $http and node app.

Unfortunately, all attempts fail T_T

Nodejs settings

    app.use(function(req, res, next) {
        res.header('Access-Control-Allow-Credentials', true);
        res.header('Access-Control-Allow-Origin', req.headers.origin);
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
        res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
        if ('OPTIONS' == req.method) {
            res.send(200);
        } else {
            next();
        }
    });

    passport.serializeUser(function(account, done) {
        done(null, account.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        Account.findById(id, function(err, account) {
            done(err, account);
        });
    });

    passport.use('local-signup', new LocalStrategy({
        usernameField: 'email'
    }, function(email, password, done) {
        ....
    }));

    passport.use('local-login', new LocalStrategy({
        usernameField: 'email'
    }, function(email, password, done) {
        ....
    }));

    app.use(morgan('dev')); // log every request to the console

    app.use(bodyParser.urlencoded({ extended: false }));

    app.use(bodyParser.json());

    app.use(cookieParser(config.app.sessionSecret));

    app.use(session({
        secret: config.app.sessionSecret,
        resave: false,
        saveUninitialized: true,
        cookie: { httpOnly: true, maxAge: 2419200000 }
    }));

    // Passport for account authentication
    app.use(passport.initialize());
    app.use(passport.session()); // persistent login sessions

    ///////////////////////////////////////////////////////////////////route controller function
    authenticate: function(req, res) {
        if (!req.isAuthenticated()) {
            res.redirect('/login');
        } else {
            res.status(200).send('successful');
        }
    }

Angular

    $http.post('http://xxxxx/login', 
      {  email: $scope.user.email,
         password: $scope.user.password
      })
    .then(function(response) {
        ...
    }, function(response) {
        ...
    });

    $http.get('http://xxxxx/authenticate',
        { withCredentials: true }).success(function() {
            ...
        })
        .error(function() {
            ... // always get here with 302 redirect
        });

My questions/things I do not understand

  1. Is that because session cookie is not set in the browser causing the problem
  2. If it relates to CORS, did I miss any settings?
  3. What else????

I solve the issue myself based on @robertklep comment. Basically, there is nothing wrong with passportjs settings. It is all about how you send the withCredentials flag in angular. Instead of calling get or post method of $http. I use the following format and it works for me

$http({
    method: 'GET',
    url: 'xxxx',
    data: {...},
    withCredentials: true
}).success ....

Reference: https://docs.angularjs.org/api/ng/service/ $http#usage

If your request to login service contains 'withCredentials' configuration option passport.js will attach credentials to the request if you provide correct login details.

$http({
method: 'POST',
url: 'http://xxxxx/login',
data: {...},
withCredentials: true})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM