Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Last active January 18, 2022 17:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/b612abdb2fd6e74dde837479f4a1ea6d to your computer and use it in GitHub Desktop.
Save xeoncross/b612abdb2fd6e74dde837479f4a1ea6d to your computer and use it in GitHub Desktop.
Breakdown of the different ways to handle OAuth flow for single-page apps like reactjs using backends on the same (or different) origin

I'm trying to handle OAuth from a react app. Rather than using an external service like Firebase or AuthO, I would like to handle OAuth login to facebook, google, twitter myself. (Regardless of the backend, OAuth libraries that can verify and trade the token for user info abound).

Here is the basic flow:

  1. React SPA opens seperate [popup/iframe/browser tab] to our server
  2. Our server creates OAuth URL payload and issues redirect to fb/google/twitter
  3. User login on fb/google/twitter redirect back to our server
  4. Our server communicates with React SPA 4.1. If same origin 4.1.1. Using localStorage 4.1.2. Using cookies 4.2. Different origin 4.2.1 using window.postMessage() 4.2.2. using URL param (or token data) with client marker of some kind in it (socket.id, session id, nounce, etc...)
  5. React SPA closes [popup/iframe/browser tab]

window.postMessage()

different origin

Since the actual browser needs to load and interact with a foreign window I've seen window.open used as the way to handle login flow. Open a popup and then do one of the following: Here is an article from 9 years ago about making a Backwards compatible window.postMessage() work for browsers older than IE 8. I would assume window.postMessage should be okay by now.

Resources

IE 11 and below

"postMessage function does not work between tabs/windows in IE8. As of IE11, this issue has not yet been fixed. Attempting to send a message to a different window or tab results in an exception with the text "Error: No such interface supported."

https://web.archive.org/web/20150309062330/http://blogs.msdn.com/b/ieinternals/archive/2009/09/16/bugs-in-ie8-support-for-html5-postmessage-sessionstorage-and-localstorage.aspx

This can be tested here: http://www.debugtheweb.com/test/xdm/origin/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment