I hava an issue ussing Passport: I'm not being able to check if a user is authenticated when calling my custom endpoints.
I have configured my Express4 application in the following way:
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// required for passport
app.use(session({ secret: 'secretphrase' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(checkAuth); // CHECK SESSION
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(prepareRequests);
The checkAuth() middleware has the following code:
var checkAuth = function(request, response, next) {
console.log("------------");
console.log("checkAuth user: " + request.session.passport.user);
console.log("checkAuth isAuthenticated: " + request.isAuthenticated());
next();
}
The first time I try to login with passport, isAuthenticated is false. Once I'm logged in, every call I do to my server, when passing thorugh my middleware, isAuthenticated is false too!!! But, the strange thing is that if I try to login again, isAuthenticated is true.
That means that only my AJAX calls return isAuthenticated = false, but when I maka a form post or click on a link to the API, it return true! Then the session is stored, but not for the AJAX request.
What I'm doing wrong? Are the cookies not being passed?