Passport.js - Browser GET requests OK, but AJAX requests from JS code aren't?

I configured Passport on the Node.js server and primarily use the Twitter authorization strategy.

I am confused by a recent discovery, similar to the fact that a GET request with a browser URL (using the web browser search bar) seems to be authenticated differently than an AJAX request from the application code. For example, if I log in using Passport, I can access everyone by pointing my browser to specific URLs that make a request directly to the server. But any Angular or jQuery request to the backend API seems unauthorized.

Could this be absolutely right? If so, how does Passport know the difference between a browser request and an AJAX request from JS code?

+5
source share
2 answers

By default, a cross-origin XHR request will not contain cookies (which are commonly used to maintain state in applications requiring authentication).

You can change this by setting withCredentials :

var xhr = new XMLHttpRequest(); xhr.open(...); xhr.withCredentials = true; 

You may need to configure CORS rules on the server to say Access-Control-Allow-Credentials: true .

See also MDN .

+4
source

Twitter's Twitter strategy requires a user to be signed in to Twitter and allow your โ€œapplicationโ€ to allow access to your Twitter account. This cannot be done using XHR, because how can a user enter their Twitter credentials to log in to Twitter if the user has not been signed up yet? How will the user approve the permissions that your Twitter โ€œappโ€ requests if the request is sent via XHR?

This applies to all Passport strategies that use OAuth or OpenID. The user browser must go directly to the site of the authorization provider so that it can either A) log into the auth provider or B) approve the permissions requested in your application. As soon as the user does what the auth provider (in your case Twitter), it redirects the user's browser back to the endpoint of your application using its token, which your application will then use to request information from the authorization provider (e.g. email address, full name, etc.)

+1
source

Source: https://habr.com/ru/post/1236113/


All Articles