Login/Authentication with OAuth2 and single-spa

Viewed 1303

I've started building a prototype for a front-end layer with single-spa. The layout is very similar to https://github.com/react-microfrontends, which means:

  • Root config
  • A navbar (React)
  • Two apps (Both React)
  • A Styleguide module
  • An API module to handle communication with a set of API

I managed to get a basic prototype running, but I now need to implement some OAuth2/OpenID based authentication, and I'm not sure where to start. I need the user redirected to a separate URL (Auth0 style) if not authenticated or not having a valid JWT, then I need a mechanism of token refresh whenever the auth token expires. On top of any general advice on best practices, existing examples and so on, I have some specific questions I can't quite work out.

  1. How can I redirect the user to a different URL when not authenticated? Which of the modules/components should be responsible for it?
  2. Is there a library that implements OAuth2 out of the box? In particular, I'm interested in some sort of automatic token refresh.
  3. What is the best way to make sure an unauthenticated/unauthorized user cannot access the app bundles?

Thanks in advance.

1 Answers

The typical approach would be to set up an Auth microfrontend that would :

  • handle credenials retrieval upon login. Be it via Password flow or OAuth ( in your case). Since you are using React, your OAuth provider should have a library that you can use within the Auth MFE to interact with it. If it's keycloak, React Keycloak is a good fit. There's no rule lf thumb here.

  • pass the credentials to your two React Apps ( Microfrontends) and the API module via Browser storage or shared state. Doing so, the API module would set the credentials in the API calls. and the two react Apps would check credentials presence before proceeding with their inner logic.

  • refresh credentials on expiration or log out user ( depending on your logic ). Loging the user would mean deleting the credentials from browser storage for example.

  • redirect to one of your react App after login. That means the Auth MFE route should always be active in the root config.

I hope it helps. Here I have summarised the flow.

auth-flow-single-spa

More of it on my github account https://github.com/exaucae/single-spa-patterns/blob/master/AUTHENTICATION.md

Related