How to save spartacus auth information in session storage instead of local storage?

Viewed 141

I have a requirement that User must log into Spartacus app every time. After doing some research I got to know that if we use 'session storage' instead of using 'local storage' then this can be achievable.

Because when browser close the auth(spartacus⚿⚿auth) information will be deleted automatically.

Can anyone please give an idea how to achieve the desired result?

1 Answers

Disclaimer: The most secure option is to avoid the persistence of the access token in the local storage or session storage. For more see https://auth0.com/docs/secure/security-guidance/data-security/token-storage#browser-in-memory-scenarios

--

To change the persistence method to SessionStorage, you need to extend the AuthStatePersistenceService and overwrite its method initSync() (see original implementation). Inside the extended method, you need to pass explicitly the storageType (if omitted, it falls back to the default LocalStorage):

@Injectable({ providedIn: 'root' })
export class CustomAuthStatePersistenceService extends AuthStatePersistenceService {
 
  initSync() {
    this.subscription.add(
      this.statePersistenceService.syncWithStorage({
        key: this.key,
        state$: this.getAuthState(),
        onRead: (state) => this.onRead(state),
        storageType: StorageSyncType.SESSION_STORAGE, // <--- pass your storage type
      })
    );
  }
}
providers: [
  {
    provide: AuthStatePersistenceService,
    useExisting: CustomAuthStatePersistenceService
  }
]
Related