How to handle user permission changes in SPA

authorizationcachingsingle-page-apps

I have a SPA which at the beginning of application startup calls the backend API, sends a JWT and asks for the access permissions of the current user. SPA then caches the permissions in-memory and uses them to check what the user is permitted to do and clears the cache when user takes an action after which the cache might become invalid (out of sync with the backend), like buying something which gives more permissions.

This worked great but now there is a new functionality which allows someone else (not the user which is currently browsing SPA) to grant (or remove) permissions for other users. This is not an issue for the backend because when a new permission is granted for user A, the backend state is immediately updated and subsequent request would check if user A has the required permissions to execute that action. The issue is that the SPA does not know that user A has a new set of permissions since the old ones are cached. That means that even though from the backend's perspective the user is allowed to execute new actions, frontend thinks that the user does not have required permissions and will prevent user from doing that action and will show an error message. This mismatch between frontend and backend would persist until user reloads the page.

  • User A is browsing the SPA website User A asks, let's say an admin,
    to grant him a permission to do X
  • Admin grants user A a permission to do X (now backend allows user A to do X) and informs user A of this
  • User A tries to do X but the frontend permission cache says that there is no permission for X and so an access denied error is shown

Any suggestions on how this can be handled? One idea is to have a list of users which need their frontend cache invalidated stored in the backend (which is a single machine). With every request, check if the user who is executing that request is in that list and if the answer is yes then "cancel" the request and return some HTTP status code which would indicate that SPA cache needs to be cleared to continue. SPA would know how to handle this response code and would clear the cache, reload the current page (or redirect to home page, or something else) and would repopulate the permission cache. This approach would seem to work but it feels somewhat hacky and complex so it would be great to hear some more insights.

Best Answer

Usually, when you work with JWT tokens, the permissions are baked into the token. So you invalidate the token as soon as the permissions change.

Whether the user needs to log in again or you find some comfortable way to swap tokens when one gets invalidated is up to you and how much work you are willing to invest.

Related Topic