Passport + Express4 not getting authenticated when using AJAX

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?

Seems that talking to Dropped.on.Caprica helps me to find the solution....

The server was logged in and saving the session succesfully. But, then, you must pass the cookie (withCredentials = true)created by Express in the following AJAX request. If you are using JQuery, in the following way:

$.ajax({
    url: 'http://127.0.0.1:3003/users/me',
    type: 'GET',
    xhrFields: {
       withCredentials: true
    }}).done(function() {
      alert( "done" );
    });

If you are not:

var request = window.XDomainRequest ? new XDomainRequest() : new XMLHttpRequest();      
var pda;
request.withCredentials = true;

Then, on every call, in your Node.JS server, asking for request.isAuthenticated() will return the right value!!!

Other tip: Don't forget to modify your response headers in the Express response to allow credentials and specify the origin to make it work in Chrome:

response.header("Access-Control-Allow-Credentials", "true");
response.header("Access-Control-Allow-Origin", "http://127.0.0.1:3008");