Last active
March 8, 2022 16:24
-
-
Save touhidrahman/12ffff7a67e451426e23503c9e0dd706 to your computer and use it in GitHub Desktop.
broadcast-channel-token-sharing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Inject, Injectable } from "@angular/core"; | |
import { WINDOW } from "@ng-web-apis/common"; | |
export const ACCESS_TOKEN_KEY = "accesToken"; | |
export const REFRESH_TOKEN_KEY = "refreshToken"; | |
@Injectable({ providedIn: "root" }) | |
export class TokenStorageService { | |
constructor(@Inject(WINDOW) private windowRef: Window) {} | |
clear() { | |
this.windowRef.sessionStorage.clear(); | |
} | |
saveAccessToken(token: string): void { | |
this.windowRef.sessionStorage.removeItem(ACCESS_TOKEN_KEY); | |
this.windowRef.sessionStorage.setItem(ACCESS_TOKEN_KEY, token); | |
} | |
saveRefreshToken(token: string): void { | |
this.windowRef.sessionStorage.removeItem(REFRESH_TOKEN_KEY); | |
this.windowRef.sessionStorage.setItem(REFRESH_TOKEN_KEY, token); | |
} | |
getAccessToken(): string | null { | |
return this.windowRef.sessionStorage.getItem(ACCESS_TOKEN_KEY); | |
} | |
getRefreshToken(): string | null { | |
return this.windowRef.sessionStorage.getItem(REFRESH_TOKEN_KEY); | |
} | |
} | |
/// APP COMPONENT /// | |
import { Component } from "@angular/core"; | |
import { TokenStorageService } from "@core/auth/services/token-storage.service"; | |
const TOKEN_SHARING_CHANNEL = "token-sharing"; | |
const REQUESTING_TOKEN = "requesting-token"; | |
@Component({ | |
selector: "app-root", | |
templateUrl: "./app.component.html", | |
}) | |
export class AppComponent { | |
bc = new BroadcastChannel(TOKEN_SHARING_CHANNEL); | |
constructor(private tokenStorageService: TokenStorageService) { | |
this.addBroadcastChannelListener(); | |
this.bc.postMessage(REQUESTING_TOKEN); | |
} | |
private addBroadcastChannelListener() { | |
this.bc.addEventListener("message", (event) => { | |
if (event.data === REQUESTING_TOKEN) { | |
new BroadcastChannel(TOKEN_SHARING_CHANNEL).postMessage({ | |
accessToken: this.tokenStorageService.getAccessToken(), | |
refreshToken: this.tokenStorageService.getRefreshToken(), | |
}); | |
} else { | |
const { accessToken, refreshToken } = event.data; | |
accessToken && this.tokenStorageService.saveAccessToken(accessToken); | |
refreshToken && this.tokenStorageService.saveRefreshToken(refreshToken); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment