【问题标题】:Typescript, Angular4: array goes empty after refreshing browserTypescript,Angular4:刷新浏览器后数组为空
【发布时间】:2023-04-05 20:33:01
【问题描述】:

我对用于在 Angular 应用程序的授权服务中存储角色的数组有疑问。我正在使用 auth0 服务登录。 auth.service.ts 看起来像这样:

  @Injectable()
export class AuthService {
  userProfile: any;
  private roles: string[] = [];
 ...
  public handleAuthentication(): void {
this.auth0.parseHash((err, authResult) => {
  if (authResult && authResult.accessToken && authResult.idToken) {
    window.location.hash = '';
    this.setSession(authResult);
    this.getRoles(authResult);
    this.router.navigate(['/']);
  } else if (err) {
    this.router.navigate(['/']);
    console.log(err);
    alert(`Error: ${err.error}. Check the console for further details.`);
  }
});}
//THIS IS getRole function
private getRoles(authResult){
let jwtHelper = new JwtHelper();
let decodedToken = jwtHelper.decodeToken(authResult.idToken);
this.roles = decodedToken['https://tobenorme.com/roles'];

}

登录后,handleAuthentication 函数被调用,一切正常,直到点击刷新按钮。然后角色数组返回空数组,我不再能够获得角色。我尝试将它们存储在本地存储中,但可以在浏览器中进行编辑。

【问题讨论】:

    标签: angular typescript jwt token auth0


    【解决方案1】:

    当您刷新并且状态消失时,您的应用程序将再次引导,正如您所提到的,将数据存储到本地存储或会话存储(最好不要以纯文本形式),当您不想这样做时,创建一个像singelton这样的方法,当角色为空时进行http调用并获取它,当角色不为空时将它们返回。使用 RxJs BehaviorSubject 是一个很好的案例。

    【讨论】:

      【解决方案2】:

      本地存储应该没问题,只要它在您的浏览器中启用。请务必使用localStorage.setItem(name, value) 存储值,并使用localStorage.getItem(name) 下次检索值。

      【讨论】:

        【解决方案3】:

        由于声明使用 JWT 令牌 (https://auth0.com/docs/jwt),您可以安全地依赖将令牌存储在本地存储或 cookie 中。 JWT 令牌经过签名,因此浏览器中的每一次本地更改都会在服务器上检测到,同时使用每个 API 调用解密令牌。

        无法避免本地更改,但服务器端应始终确保用户实际拥有提供的角色/权限。

        您可以参考以下示例:https://github.com/auth0/angular2-jwt

        【讨论】:

          【解决方案4】:

          也许它会帮助我这样解决的人:

          private getRoles(authResult){
              let jwtHelper = new JwtHelper();
              let decodedToken;
              if (authResult && authResult.accessToken && authResult.idToken){
                  decodedToken = jwtHelper.decodeToken(authResult.idToken);
                  this.roles = decodedToken['https://tobenorme.com/roles'];
              }else if(this.isAuthenticated && authResult){
                decodedToken = jwtHelper.decodeToken(authResult);
                this.roles = decodedToken['https://tobenorme.com/roles'];
              }
          

          我必须在构造函数中调用这个函数。

          【讨论】:

            猜你喜欢
            • 2017-09-10
            • 1970-01-01
            • 1970-01-01
            • 2010-09-08
            • 2011-07-14
            • 1970-01-01
            • 2019-01-16
            • 1970-01-01
            • 2014-08-10
            相关资源
            最近更新 更多