Search code examples
angularoauth-2.0keycloakpkceangular-oauth2-oidc

Is it a good practice to store token in browser sessionStorage?


Which of the browser provided client-side storage option is better?


Solution

  • Storage of an access token within local storage depends on the visibility of your application. Is it a public facing web application or an internal organization web application?

    If a public facing web application, then the access token should as a minimum have a short expiry duration. This is to minimize the possibility of an active session being accessible to other users that share the same machine.

    Alternatively, you can use sessionStorage (see https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage)

    which keeps the value stored until the browser window or browser tab is closed. This is slightly better then using localStorage (see https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)

    Aside from using browser local or session storage, you can implement your own backend session management service or use a cloud based session storage provider such as Auth0 or Okta to handle the storage for you. Then you won't have to worry about session hijacking of a browser's stored tokens. This is recommended for high use, high visibility public facing web applications.

    Reading user details can be done when you obtain the access token from your identity server when the user is authenticated. Then you will not have to execute additional requests to obtain other user details.