Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/451.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 令牌在应用程序启动时刷新,但未计划再次刷新_Javascript_Angular_Typescript_Ionic Framework - Fatal编程技术网

Javascript 令牌在应用程序启动时刷新,但未计划再次刷新

Javascript 令牌在应用程序启动时刷新,但未计划再次刷新,javascript,angular,typescript,ionic-framework,Javascript,Angular,Typescript,Ionic Framework,登录后,调用schedulefresh()函数,它将持续刷新令牌。当我刷新页面时,或者当经过身份验证的用户再次尝试访问该网页时,就会出现问题startupTokenRefresh在启动时被调用,令牌被刷新,但令牌不会像其假定的那样被再次刷新。如果我在知道令牌已过期后刷新页面,我会收到一个token\u not\u provided错误,但我可以在网络控制台中看到该令牌在该错误或页面加载几秒钟后正在刷新。如果我再次刷新,对我的api的请求就可以了,但是令牌在过期后不会再次刷新 我做错了什么 app

登录后,调用
schedulefresh()
函数,它将持续刷新令牌。当我刷新页面时,或者当经过身份验证的用户再次尝试访问该网页时,就会出现问题
startupTokenRefresh
在启动时被调用,令牌被刷新,但令牌不会像其假定的那样被再次刷新。如果我在知道令牌已过期后刷新页面,我会收到一个
token\u not\u provided
错误,但我可以在网络控制台中看到该令牌在该错误或页面加载几秒钟后正在刷新。如果我再次刷新,对我的api的请求就可以了,但是令牌在过期后不会再次刷新

我做错了什么

app.component.ts(应用程序启动时)

auth.service.ts

jwtHelper: JwtHelper = new JwtHelper();
token;
refreshSubscription: any;
authNotifier: ReplaySubject<boolean> = new ReplaySubject<boolean>(1);

authenticationNotifier(): Observable<boolean> {
    return this.authNotifier;
}

refresh(): Observable<any> {
    console.log("in refresh()");
    let URL = `${myApi}/refresh?token=${this.token}`;

    return this.authHttp.get(URL)
      .map((rsp) => {
          this.token = rsp.json().token;
          this.storage.ready().then(() => this.storage.set('token', this.token));
          this.authNotifier.next(true);
          return rsp.json().token;
        },
        err => {
          this.authNotifier.next(false);
          this.logout();
          console.log(err);
        })
      .share();
}

checkToken() {
    if (this.token === '' || this.token === null || this.token === undefined) {
      this.authNotifier.next(false);
      this.logout();
    }
}

public scheduleRefresh() {
  if (this.token === '' || this.token === null || this.token === undefined) {
    this.authNotifier.next(false);
    this.logout();
  }
  else {

    // If the user is authenticated, use the token stream provided by angular2-jwt and flatMap the token
    let source = this.authHttp.tokenStream.flatMap(
      token => {
        let jwtIat = this.jwtHelper.decodeToken(this.token).iat;
        let jwtExp = this.jwtHelper.decodeToken(this.token).exp;
        let iat = new Date(0);
        let exp = new Date(0);

        let delay = (exp.setUTCSeconds(jwtExp) - iat.setUTCSeconds(jwtIat));

        return Observable.interval(delay);
      });

    this.refreshSubscription = source.subscribe(() => {
      this.refresh().subscribe((res) => console.log('-> Refreshed...'), 
      (error) => console.log('Refresh error: ' + JSON.stringify(error)))
    });
  }
}

public startupTokenRefresh() {
  if (this.token === '' || this.token === null || this.token === undefined) {
    this.authNotifier.next(false);
    this.logout();
  }
  else {
      // Get the expiry time to generate a delay in milliseconds
      let now: number = new Date().valueOf() / 1000;
      let jwtExp: number = this.jwtHelper.decodeToken(this.token).exp;
      let iat: number = this.jwtHelper.decodeToken(this.token).iat;

      let refreshTokenThreshold = 10; //seconds

      let delay: number = jwtExp - now;
      let totalLife: number = (jwtExp - iat);
      (delay < refreshTokenThreshold ) ? delay = 1 : delay = delay - refreshTokenThreshold;

      // Use the delay in a timer to // run the refresh at the proper time
      return Observable.timer(delay * 1000);
      });

    // Once the delay time from above is reached, get a new JWT and schedule additional refreshes
    source.subscribe(() => {
      this.refresh().subscribe(
        (res) => {
          console.log('-> Refreshed on startup');
          this.scheduleRefresh();
        },
        (error) => console.log('-> Refresh error:' + JSON.stringify(error)))

    });
  }
}

public unscheduleRefresh() {
  console.log("unsched");
  if (this.refreshSubscription) {
    this.refreshSubscription.unsubscribe();
  }
}
jwtHelper: JwtHelper = new JwtHelper();
token;
refreshSubscription: any;
authNotifier: ReplaySubject<boolean> = new ReplaySubject<boolean>(1);

authenticationNotifier(): Observable<boolean> {
    return this.authNotifier;
}

refresh(): Observable<any> {
    console.log("in refresh()");
    let URL = `${myApi}/refresh?token=${this.token}`;

    return this.authHttp.get(URL)
      .map((rsp) => {
          this.token = rsp.json().token;
          this.storage.ready().then(() => this.storage.set('token', this.token));
          this.authNotifier.next(true);
          return rsp.json().token;
        },
        err => {
          this.authNotifier.next(false);
          this.logout();
          console.log(err);
        })
      .share();
}

checkToken() {
    if (this.token === '' || this.token === null || this.token === undefined) {
      this.authNotifier.next(false);
      this.logout();
    }
}

public scheduleRefresh() {
  if (this.token === '' || this.token === null || this.token === undefined) {
    this.authNotifier.next(false);
    this.logout();
  }
  else {

    // If the user is authenticated, use the token stream provided by angular2-jwt and flatMap the token
    let source = this.authHttp.tokenStream.flatMap(
      token => {
        let jwtIat = this.jwtHelper.decodeToken(this.token).iat;
        let jwtExp = this.jwtHelper.decodeToken(this.token).exp;
        let iat = new Date(0);
        let exp = new Date(0);

        let delay = (exp.setUTCSeconds(jwtExp) - iat.setUTCSeconds(jwtIat));

        return Observable.interval(delay);
      });

    this.refreshSubscription = source.subscribe(() => {
      this.refresh().subscribe((res) => console.log('-> Refreshed...'), 
      (error) => console.log('Refresh error: ' + JSON.stringify(error)))
    });
  }
}

public startupTokenRefresh() {
  if (this.token === '' || this.token === null || this.token === undefined) {
    this.authNotifier.next(false);
    this.logout();
  }
  else {
      // Get the expiry time to generate a delay in milliseconds
      let now: number = new Date().valueOf() / 1000;
      let jwtExp: number = this.jwtHelper.decodeToken(this.token).exp;
      let iat: number = this.jwtHelper.decodeToken(this.token).iat;

      let refreshTokenThreshold = 10; //seconds

      let delay: number = jwtExp - now;
      let totalLife: number = (jwtExp - iat);
      (delay < refreshTokenThreshold ) ? delay = 1 : delay = delay - refreshTokenThreshold;

      // Use the delay in a timer to // run the refresh at the proper time
      return Observable.timer(delay * 1000);
      });

    // Once the delay time from above is reached, get a new JWT and schedule additional refreshes
    source.subscribe(() => {
      this.refresh().subscribe(
        (res) => {
          console.log('-> Refreshed on startup');
          this.scheduleRefresh();
        },
        (error) => console.log('-> Refresh error:' + JSON.stringify(error)))

    });
  }
}

public unscheduleRefresh() {
  console.log("unsched");
  if (this.refreshSubscription) {
    this.refreshSubscription.unsubscribe();
  }
}
onLogin() {
  this.authService.login(this.loginForm.value.username, this.loginForm.value.password)
    .subscribe(
    (response) => {
        this.storage.ready().then(() => this.storage.set('token', response.token));
        this.authService.token = response.token;
        this.authService.authNotifier.next(true);
      },
      error => {
        console.log(error);
        this.loginError = true;
        this.authService.authNotifier.next(false);
      },
      () => {
        console.log("login success");
        this.authService.scheduleRefresh();
        this.navCtrl.push(TabsPage);
      },
    );
    }
}