How to keep logged in when open other tab with angular-oauth2-oidc?

2.1k Views Asked by At

I'm implementing login feature in angular using

angular-oauth2-oidc

and IndentityServer4 (.Net core). If I open tab A and logged in then I open other tab and go to my site, but the browser redirects to login page while I want it to keep stay in the home page. Here is my code :

ngOnInit() {
    this.checkLogin();
    this.getLoginData();
  }

  checkLogin() {
    console.log({ TOKEN: this.oauthService.getAccessToken() })
    if (this.oauthService.getAccessToken() != null) {
      this.router.navigateByUrl('/home');
    } else {
      return;
    }
  }

  Login() {
    this.oauthService.fetchTokenUsingPasswordFlow(this.username, this.password).then((resp) => {
      return this.oauthService.loadUserProfile();
    }).then(() => {
      let claims = this.oauthService.getIdentityClaims();
      if (claims) console.log(claims);
      this.rememberMe();
      this.toastr.success("Login successful !");
      this.router.navigateByUrl('/home');
    }).catch((err) => {
      this.toastr.error(err.error.error_description)
    })
  }


  rememberMe() {
    if (this.remember_me) {
      this.cookieService.set('uSnGTX23NJKLX=', this.username);
      this.cookieService.set('pWNEAExy2HBXS=', this.password);
    } else {
      this.cookieService.deleteAll();
    }
  }

  private getLoginData() {
    this.username = this.cookieService.get('uSnGTX23NJKLX=');
    this.password = this.cookieService.get('pWNEAExy2HBXS=');
    this.remember_me = (this.username != '' || this.password != '');
  }

Does anyone have any idea? Thanks!

1

There are 1 best solutions below

0
On
  1. Try to store the logged info in localStorage.
  2. Use oauth service together with angular guards: https://github.com/katerinalev1992/Angular6Firebase/blob/master/src/app/services/auth-guard.service.ts