How to secure an SPA which fetch data from REST api? Does every authentication needs to be done at backend?

I am having spring-boot powered REST Apis which are used by my Single Page Application build using React.js.

I now want to add authentication layer to it. I am already using JWT for it but I need to replace it with Auth0. But I am very much confused on how the flow should be like. All the API endpoints are secured and only authenticated user have access to them.

Since Auth0 also provide browser support where everything from login, signup redirect etc are handled out of the box my Auth0, should I use IDP directly into my browser client or should the backend(REST) handle these?
Every request to the backend should be validated for authentication.

Hi @PTanwarCS,

Typically with a SPA, authentication looks like this:

  1. The user logs into Auth0 which acts as the authorization server (e.g. Universal Login)
  2. Auth0 redirects the user back to the SPA along with a code
  3. The SPA requests tokens using the code
  4. Auth0 issues two tokens, an ID Token and an Access Token

This process is simplified with Auth0 SDKs such as the React SDK. If you haven’t checked it out already, you may want to take a look at the React Quickstart or the Complete Guide to React Authentication

The React app can use the ID Token to find data on the user such as their name, email, etc. The Access Token is used for calling an API.

When you register your API with Auth0 and provide an audience when you initialize the Auth0Provider, then Auth0 will issue you a JWT Access Token that can be used with your API as a bearer token. Your API can validate the JWT Access Token to ensure it was issued by Auth0.

    <App />

Since it sounds like you have multiple APIs and you can only pass one audience to the Auth0Provider, you may want to look into this solution: Represent Multiple APIs Using a Single Logical API

Here is an architecture scenario that may be helpful for a SPA + API: SPA + API

Thanks for your response.
Shouldn’t the backend API be responsible for connecting with Auth0? I don’t want to redirect to the Auth0 login page. In that case everything should be handled by my backend API, shouldn’t it?

Universal Login is the recommended approach, but you can configure an embedded login: Embedded Login

Note: Browsers such as Safari block third-party cookies, so you will need to use a Custom Domain to manage CORS issues.

Your API can handle the authentication if the SPA meets the following criteria:

  • It is served to the client using your own backend.
  • It has the same domain as your backend.
  • It makes API calls that require authentication to your backend.

Here is the full documentation: Authenticate Single-Page Apps With Cookies

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.