首页 > 解决方案 > JWT 令牌尚未生效

问题描述

我的 Angular Web 应用程序中有一个谷歌登录按钮。成功登录后,我存储用户配置文件和 id-token。id-token 在我发送到自定义 api 的每个请求标头中设置。

我目前遇到以下代码的 2 个问题:

onGoogleSignInSuccess(event: GoogleSignInSuccess) {
var profile = event.googleUser.getBasicProfile();
var id_token = event.googleUser.getAuthResponse().id_token;

// store google user data in local storage
localStorage.setItem('googleUserProfile', JSON.stringify(profile));
localStorage.setItem('googleIdToken', JSON.stringify(id_token));

// check user's email address exist in Felix
this.userService.getUserByEmail(profile.getEmail()).subscribe(InUser => {
  this.globalService.setCurrentUser(InUser);
  this.router.navigate(['companylist']);
}, error => {
  this.errorLoggingIn = true;
  this.errorCode = error.status;
  console.log('error logging in: ' + JSON.stringify(error));
});
}
  1. 大多数情况下,我的 API 在尝试使用 google 验证 id-token 时会抛出“JWT not yet valid”错误。它似乎每 4 次尝试一次。
  2. 导航到“companyList”时,它没有击中 ngOnInit

但是,当我使用 npm 模块 sngular5-social-auth 并实现以下代码时:

public socialSignIn(socialPlatform: string) {
let socialPlatformProvider;
socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;

this.socialAuthService.signIn(socialPlatformProvider).then(
  (userData) => {
    console.log(socialPlatform + " sign in data : ", userData);
    // store google user data in local storage
    localStorage.setItem('currentGoogleUserData', JSON.stringify(userData));

    this.userService.getUserByEmail(userData.email).subscribe(InUser => {
      this.globalService.setCurrentUser(InUser);
      this.router.navigate(['companylist']);
    }, error => {
      this.errorLoggingIn = true;
      this.errorCode = error.status;
      console.log('error logging in: ' + JSON.stringify(error));
    });
  }
);
}

一切似乎都很好。我没有收到 JWT not yet valid 错误,而且我的公司列表页面可以很好地加载数据。

我决定使用选项 1,因为我得到了默认的 google 登录按钮。

任何想法这两个代码之间的区别是什么?

标签: angularjwtgoogle-signin

解决方案


问题是您的服务器时间与 Google 服务器时间不同。当您验证从谷歌收到的令牌时,该令牌可能会在 1 秒或 n 秒内有效。这就是为什么你得到一个错误JWT not yet valid

要修复它,您可以将服务器时间与谷歌服务器时间同步。谷歌文档如何做到这一点是https://developers.google.com/time/


推荐阅读