为什么刷新页面或单击Angular应用程序中的链接时,我的auth0令牌过期? [英] Why my auth0 token expires when refreshing page or clicking link in my Angular app?

查看:113
本文介绍了为什么刷新页面或单击Angular应用程序中的链接时,我的auth0令牌过期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Angular SPA中设置身份验证.

I'm setting up authentication in my Angular SPA.

我正在使用auth0,并且正在查看其页面上的教程: https://auth0.com/docs/quickstart/spa/angular2

I'm using auth0 and I was going through a tutorial on their page: https://auth0.com/docs/quickstart/spa/angular2

我做了登录教程.

import { Injectable } from '@angular/core';
import * as auth0 from 'auth0-js';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  userProfile: any;

  private _idToken: string;
  private _accessToken: string;
  private _expiresAt: number;

    auth0 = new auth0.WebAuth({
    clientID: '*****',
    domain: '****',
    responseType: 'token id_token',
    redirectUri: 'http://localhost:4200/callback',
    scope: 'openid profile'
  });

  constructor(public router: Router) {
    this._idToken = '';
    this._accessToken = '';
    this._expiresAt = 0;
  }

  public login(): void {
    this.auth0.authorize();
  }

  public handleAuthentication(): void {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        window.location.hash = '';
        this.localLogin(authResult);
        this.router.navigate(['/']);
      } else if (err) {
        this.router.navigate(['/']);
        console.log(err);
      }
    });
  }

  public getProfile(cb): void {
    if (!this._accessToken) {
      throw new Error('Access Token must exist to fetch profile');
    }

    const self = this;
    this.auth0.client.userInfo(this._accessToken, (err, profile) => {
      if (profile) {
        self.userProfile = profile;
      }
      cb(err, profile);
    });
  }

  private localLogin(authResult): void {

    localStorage.setItem('isLoggedIn', 'true');

    const expiresAt = (authResult.expiresIn * 1000) + new Date().getTime();
    this._accessToken = authResult.accessToken;
    this._idToken = authResult.idToken;
    this._expiresAt = expiresAt;
  }

  public renewTokens(): void {
    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 {
    this._accessToken = '';
    this._idToken = '';
    this._expiresAt = 0;

    localStorage.removeItem('isLoggedIn');
    this.router.navigate(['/']);
  }

  public isAuthenticated(): boolean {
    return new Date().getTime() < this._expiresAt;
  }

  get accessToken(): string {
    return this._accessToken;
  }

  get idToken(): string {
    return this._idToken;
  }


}

我单击页面上的登录,我成功了,我获得了令牌,一切都很好.但是,当我刷新页面或单击链接时,注销了.我该怎么做才能保持登录页面?

I click login on my page, I'm successful, I got token and everything is fine. But when I refresh the page or click a link is getting logged out. What should I do to stay logged in the page?

推荐答案

当前,您正在将数据保存在内存变量中.因此,当您重新加载应用程序时,内存变量( _expiresAt )会丢失该值.因此, isAuthenticated()方法返回 false .您可以将数据保存在浏览器 localStorage 中.

Currently, you are saving the data in the in-memory variable. So, when you reload the application, the in-memory variable (_expiresAt) lost the value. Therefore, isAuthenticated() method returns false. You can save the data in the browser localStorage.

 private localLogin(authResult): void {
      const expiresAt = JSON.stringify(
      authResult.expiresIn * 1000 + new Date().getTime()
    );

    localStorage.setItem("access_token", authResult.accessToken);
    localStorage.setItem("id_token", authResult.idToken);
    localStorage.setItem("expires_at", expiresAt);
  }

然后,在 isAuthenticated()方法中,您可以从localStorage加载expiresAt.

Then, in the isAuthenticated() method, you can load the expiresAt from the localStorage.

  public isAuthenticated(): boolean {
    const expiresAt = JSON.parse(localStorage.getItem("expires_at") || "{}");
    return new Date().getTime() < expiresAt;
  }

注销期间,您需要清除localStorage中的数据.

During the log out, you need to clear the data from localStorage.

public logout(): void {
    // Remove tokens and expiry time from localStorage
    localStorage.removeItem("access_token");
    localStorage.removeItem("id_token");
    localStorage.removeItem("expires_at");
    // Remove server SSO session
    this.auth0.logout({ returnTo: "http://localhost:4200" });

  }

最佳做法:

对于SPA,请遵循auth0最佳做法: https://auth0 .com/docs/security/store-tokens#single-page-apps

For SPA, follow auth0 best practice: https://auth0.com/docs/security/store-tokens#single-page-apps

这篇关于为什么刷新页面或单击Angular应用程序中的链接时,我的auth0令牌过期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆