【问题标题】:Auth0 accessToken missing when Refresh刷新时缺少 Auth0 accessToken
【发布时间】:2019-05-21 20:58:57
【问题描述】:

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

Debugging when Refresh

我在 Allowed Web Origins

上添加了 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放到renew token或者logout的功能里面了,进不去。

 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;
  }

【问题讨论】:

  • 这段代码在哪里?公共注销()。如果它在 AppComponent 中,那么它将被执行。尝试删除它并放入服务
  • @JackM 注销功能在服务中
  • 您是否将令牌保存在 localStorage 中?如果没有,保存令牌,并在页面加载时检查密钥是否存在并相应地更新您的状态
  • @MaxSvid 是的,我试过了。我用代码编辑

标签: angular auth0 page-refresh


【解决方案1】:

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

【讨论】:

  • 是的,我试过了,但它不起作用。我用代码编辑。
  • 从代码中移除 If 块 (if(!this._accessToken))。
  • 也不工作。而且函数的行为也不好
  • 能分享一下功能码吗??还请检查存储在本地存储中的值。
  • 我已经检查了这些值并且是正确的,但是 isAuthenticated() 返回 false。我已经分享了代码。谢谢
猜你喜欢
  • 1970-01-01
  • 2016-11-02
  • 2019-05-29
  • 2017-08-11
  • 2021-05-30
  • 2017-09-29
  • 1970-01-01
  • 2018-03-29
  • 2020-05-12
相关资源
最近更新 更多