刷新时缺少Auth0 accessToken

时间:2019-05-21 10:38:33

标签: angular auth0 page-refresh

登录效果很好,但是当我刷新页面时,它会注销。

Debugging when Refresh

我在允许的网络起源

上的Auth0配置中添加了http://localhost:4200
export class AppComponent implements OnInit {


  constructor(public auth: AuthService) {
    auth.handleAuthentication();
  }

  ngOnInit() {
    if (this.auth.isAuthenticated()) {
      this.auth.renewTokens();
    }
  }

}

它不显示任何错误消息。我已经将console.log放入了续订令牌或注销的功能中,并且它没有输入。

 public renewTokens(): void {
    console.log("adios3");
    this.auth0.checkSession({}, (err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.localLogin(authResult);
      } else if (err) {
        alert(`Could not get a new token (${err.error}: ${err.error_description}).`);
        this.logout();
      }
    });
  }

  public logout(): void {
    // Remove tokens and expiry time
    console.log("adios1");
    this._accessToken = '';
    this._idToken = '';
    this._expiresAt = 0;

    this.auth0.logout({
      returnTo: window.location.origin
    });
  }

  public isAuthenticated(): boolean {
    console.log("adios4");
    // Check whether the current time is past the
    // access token's expiry time
    return this._accessToken && Date.now() < this._expiresAt;
  }

更新:我已经尝试过了,但是仍然无法使用

private localLogin(authResult): void {
    // Set the time that the Access Token will expire at
    const expiresAt = (authResult.expiresIn * 1000) + Date.now();
    this._accessToken = authResult.accessToken;
    this._idToken = authResult.idToken;
    this._expiresAt = expiresAt;
    localStorage.setItem('accessToken',this._accessToken);
localStorage.setItem('expiresAt',String(this._expiresAt));
  }
   public isAuthenticated(): boolean {
    console.log("adios4");
    this._accessToken = localStorage.getItem('accessToken');
    this._expiresAt = Number(localStorage.getItem('expiresAt'));
    return this._accessToken && Date.now() < this._expiresAt;
  }

1 个答案:

答案 0 :(得分:0)

您的访问令牌存储在哪里。是在AppComponent还是Service中?在页面刷新时将令牌保存在本地存储中,您的访问令牌将设置为“”。在“身份验证”中,从本地存储读取令牌密钥。