I'm trying to implement social login functionality in a MERN SPA so that users can login to my site using their Google/Facebook/Twitter/etc. login. This is clearly a very common scenario, and there are tons of posts and examples that address how to accomplish this using various authentication flows (i.e. authorization code flow, authorization code flow with PKCE, etc.)
However, for the flow I am trying to implement (described below), I cannot get my head around how to handle the redirect back from the identity provider without causing the user agent to refresh and lose state.
For example, here is the flow I am trying to implement for logging in with Google:
User clicks "Login with Google" button, which directs user agent to Google's authorization endpoint.
Google authenticates user and redirects them back to my redirect URI with an authorization code.
User agent makes API call to backend of my site providing the authorization code.
Backend of my site sends authorization code to Google's token endpoint (along with my app's
client_id
andclient_secret
), gets back ID token, creates suitable JWT, and returns that JWT back to user agent.User agent stores JWT and sends it as bearer token in all subsequent calls back to server.
The problem I have is at step 2. Since this step causes the browser to reload my SPA, the state in the React components gets cleared. I can partially get around this using localStorage
, but that adds complexity.
Is it possible to implement this flow without the browser having to reload my app and clearing component state? Or, is there some other approach I should be using that gets around this apparent pitfall?
(I am new to React/SPAs and OIDC, so please excuse any glaring misconceptions or oversights.)