Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS|SailsJS|PassportJS AJAX Authentication: Making Successive Requests for Data

Making Successive Requests for Data

TL;DR

After authentication, I cannot request data from my app's Front-End -- but only through server-side views and Postman can I make subsequent requests for data after logging in, or by authenticating my user in Postman and then making the data request in my app.

First off, I'm a newbie on the server-side.

I've a SailsJS backend which I'm using for REST. Creating and authenticating a user, using LocalStrategy, works fine -- and really, even making subsequent requests for data works fine -- but not via AJAX from my app.

I can use Postman or server-side views to access data, such as /list; making requests after authentication in my app doesn't work -- UNLESS I jump back into Postman and login, then jump back to my app and remake the request.

I do notice that my set-cookie's in my app are different between the first authentication request and the request for /list.

If necessary, I can show some code, but this seems I'm missing a very high-level, basic concept in making authenticated AJAX requests.

EDIT: My front-end is on a different domain -- Sails runs on localhost:1337 while my UI runs on localhost:8100.

Here's what my /api/config/cors.js looks like:

module.exports.cors = {

  allRoutes: true,

  origin: '*',

  credentials: true,

  // methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',

  // headers: 'content-type'

};

I'm using angular on the front-end, and the subsequent requests are using withCredentials: true -- do I need to add this to the login request too? Must I send the username/email along in the request also?

How do I allow all my subsequent requests for data authenticated after login?

like image 906
Cody Avatar asked Nov 20 '25 14:11

Cody


1 Answers

If your frontend application has as a different origin than your backend application the AJAX requests will not include the session cookie by default.

If you are using jQuery:

$.ajax({
   url: a_cross_domain_url,
   xhrFields: {
      withCredentials: true
   }
});

This option has to be used for all AJAX requests, so the server can treat them as belonging to the same session.

You also have to configure the server side to allow CORS requests.

like image 179
Alexis N-o Avatar answered Nov 24 '25 22:11

Alexis N-o