'Handling JWT in Angular?

I have an UI application with Angular(v12.0) and Spring Boot(v 2.5) in the backend. Currently we only send app credentials in authorization headers. But recently a backend service that our spring boot uses to retrieve and update data has configured a JWT in the response and is asking us to save and send it in headers for every subsequent request.(We use this service number of times for a user).

So we had thought of following approach and implemented it:

  1. Save the Authorization header from the initial response in Angular in a session Storage item.
  2. Send it in request header for every subsequent call.

But the issue with session Storage is that we use it mostly for internal customers and they usually launch the app within the same tab for multiple customers and because the token still persists for the previous end user, it is throwing authorization error.

So I was thinking if there is any other better approach to achieve this goal instead of session Storage may be in Angular or Spring. I have also tried following in angular:

 @HostListener('window:unload', ['$event'])
    unloadHandler(event) {
        window.sessionStorage.clear();
    }

But it clears every time a browser refresh happens and we do not want that. Any inputs on how to resolve it are appreciated.



Solution 1:[1]

Why wouldn't a Singleton service work here? It'd keep the token scoped by "loaded app" and it wouldn't ever be persisted.

@Injectable({providedIn: 'root'})
export class TokenStorageService {
  private _token: string | null = null;
  set token(str: string) { this._token = value }
  get token(): string|null { return this._token }
  clearToken() { this._token = null }
}

And then from somewhere else. Let's say a guard:

export class SomeGuard implements CanActivate {

  constructor(private tokenService: TokenStorageService) {}

  canActivate(...) { return this.tokenService.token != null }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Some random IT boy