How to change the default token storage method of Spartacus

The default storage method of Spartacus is localStoragethat we can replace it with SessionStorage.

Default implementation: AuthStatePersistenceService:

/**
   * Initializes the synchronization between state and browser storage.
   */
  public initSync() {
    
    
    this.subscription.add(
      this.statePersistenceService.syncWithStorage({
    
    
        key: this.key,
        state$: this.getAuthState(),
        onRead: (state) => this.onRead(state),
      })
    );
  }

Create a new one CustomAuthStatePersistenceService, overloading AuthStatePersistenceServicethe initSyncmethod of :

@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, // 此处传入自定义的 storage 类型
      })
    );
  }
}

Then replace in the providersarea :

providers: [
  {
    
    
    provide: AuthStatePersistenceService,
    useExisting: CustomAuthStatePersistenceService
  }
]

Guess you like

Origin blog.csdn.net/i042416/article/details/124415565