Using Code Grant with SPA + REST API

(Possible duplicate of SPA with Authorization Code Grant, but the wording in that post is a little ambiguous)

Our web app is a staticly served SPA that makes calls to a backend REST API for all of its data. We used to use the Auth0 implicit grant, until we realized we couldn’t prolong the 3 day inactivity reset, which was a dealbreaker for us. To get our auth functional as quickly as possible, we converted to using the code grant, where:

  • SPA authorizes with Auth0 using lock.js and passwordless phone auth
  • If successful, SPA window reloads and receives auth code
  • SPA sends auth code to backend REST API, which then uses code to get access token and refresh token from Auth0
  • Refresh token is stored in database. Access token is sent back to the SPA
  • Whenever the SPA detects that the current access token is expired, it makes a call to the API to get a new access token. The API fetches from the database the refresh token associated with the expired access token and returns a new access token

This is a little janky because the SPA has to wait for the backend to send back an access token before it can pull any data, but it seems secure. Critically, the browser never sees the refresh token. Is there anything wrong with this flow?

You don’t say how you authorize the request to get a new access token for the SPA from the backend API once the old token is expired. But if you have a backend that can keep sessions and cookies (i.e it’s in the same domain as the SPA application), I would rather keep the access token away from the browser altogether, and authorize all the requests to the API with cookies.

You use the authorization code flow and process the authorization response in the backend. If successful, you create a session cookie that the SPA can present on every request, and thus no need for access tokens in the browser.

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