Oauth/authentication redirect and CORS

oauth

#1

Per the instructions here, I’m attempting to redirect the user’s browser to the oauth/authenticate API endpoint. Server-side I’ve already gotten a request token. User clicks their link, and I send them a redirect. The browser receives the following response:

Fetch API cannot load https://api.twitter.com/oauth/authenticate?oauth_token={token}. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Is it really possible that Twitter team outright tells developers to redirect users in the browser, while on the other hand disallowing CORS on this API endpoint? I must be doing something wrong here, because that truly makes no sense.


#2

So, I figured out a solution to this.

Sending a 302 Redirect from the server back to the client is not the way to do this. What I did instead was: send the full url for the oauth/authenticate API call (ie, https://api.twitter.com/oauth/authenticate?oauth_token=xxxxxxxxxxx) back to the client. Then, have the client take the body of that, and manually set window.location to the received url. Here’s the sample of the client-side javascript:

const loginButton = document.getElementById('login-button');

loginButton.addEventListener('click', event => {
  fetch('twitter/login')
    .then(res => res.text())
    .then(url => {
      window.location = url;
    });
});

Possibly not ideal, but it works and doesn’t seem to cause any problems. I spent too long spinning my wheels on this, so I’m sure this can help somebody. :slight_smile: