Search code examples
node.jsreactjsexpressoauth-2.0instagram-api

How to let frontend know your server has successfully retrieved an access token


I've been studying the OAuth 2.0 authorization code flow and am trying to write a React application with an Express backend that displays what a user would see on their own Instagram profile. I'm trying to do so with minimal external libraries (i.e. not using passport-js) and without bringing a database into the mix.

This is my flow as of now:

  1. Resource owner clicks an <a> tag on the React application (port 3000) which redirects them to the /auth/instagram endpoint of my Express server (port 8000)

  2. res.redirect(AUTHORIZATON_URL) sends them to Instagram's authorization server

  3. Resource owner consents and the authorization code is sent back to the predefined redirect-url /auth/instagram/callback with the authorization code set as a query parameter

  4. I strip the authorization code off the url and make a POST request to https://api.instagram.com/oauth/access_token to grab the access token

Now that I have the access token, how do I reach out to the React frontend to let them know that everything worked and that the user was successfully authenticated?

From what I've read, this is where the idea of sessions and cookies come into play, but I haven't had luck finding documentation on how to achieve what I want without bringing in third party libraries.

In the end, I would like for my app to support multiple users viewing their profiles simultaneously. Since I imagine passing the access token to the frontend defeats the purpose of securely retrieving it on the backend, I'm guessing I will somehow need to pass a session id between the frontend and backend that is somehow linked to an access token.

Any ideas as to what my next steps should be are greatly appreciated, as well as any articles or documentation you see fit. Thanks!


Solution

  • Since you're doing the OAuth authentication on the server side, you have to pass some parameter to the redirect_uri, identifying the user session (see: Adding a query parameter to the Instagram auth redirect_uri doesn't work? ); When the redirect uri is called from the authority server, you will know which user was authorized. To notify the browser there are two options: 1) Notify the client using web sockets; 2) Pull the state from the client using a timer triggered function;