Search code examples
oauth-2.0single-sign-onmicroservicesopenid-connectidentityserver4

Can I use Oauth2 Authorization Code flow for a SPA (React app), if I have a server-side proxy?


After watching an obscene amount of tutorials on OAuth2, there is one best practice that everyone repeatedly states - if you have a React app (or Angular, or Ember) - you must use Implicit flow with it.

I understand that storing client credentials in publicly visible javascript would not work. However, my scenario is a bit different:

  1. I'm only using Oauth2 for single sign on and token generation for microservices. I chose it instead of simply generating tokens, since well-supported third party libraries are built around the Oauth2 idea.
  2. My idea is to have a React app, and a ASP.NET MVC app which serves the javascript and acts as a proxy for API requests. The user authenticates for the server-side app (by using Oauth2 authorization code flow).
  3. Then if I need to retrieve data from an API, I call my ASP.NET MVC app from React (by sending a simple cookie). The MVC app holds the token without ever exposing it to the user's browser.
  4. Obviously, when called, my MVC app then redirects the request to the necessary API, providing the bearer token.

To better understand why this is what I came up with, here are some requirements I've received that might be unusual:

  1. I really don't want the access token to be shared - even if it's relatively short lived.
  2. I also want to be able to limit each user account to 3 concurrent user sessions. Easy to do using cookies and server-side sessions.

I can't wrap my head around why this idea would be that bad. Is there any technical problem that might prevent this from working? Or maybe a security risk?


Solution

  • The authorization code flow returns an authorization code (like it says on the tin) that can then be exchanged for an ID token and access token. This requires client authentication using a client id and secret to retrieve the tokens from the back end and has the benefit of not exposing tokens to the User Agent.

    This flow allows for long lived access (through the use of refresh tokens). Clients using this flow must be able to maintain a secret.

    Accordingly to your description, you have service-to-service authorization flow, and as your service are not exposing client secret key it is totally OK to use the Code flow. Moreover, you should use it to allow long lived tokens.