angular - 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));
});
}
- 大多数情况下,我的 API 在尝试使用 google 验证 id-token 时会抛出“JWT not yet valid”错误。它似乎每 4 次尝试一次。
- 导航到“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 登录按钮。
任何想法这两个代码之间的区别是什么?
解决方案
问题是您的服务器时间与 Google 服务器时间不同。当您验证从谷歌收到的令牌时,该令牌可能会在 1 秒或 n 秒内有效。这就是为什么你得到一个错误JWT not yet valid
要修复它,您可以将服务器时间与谷歌服务器时间同步。谷歌文档如何做到这一点是https://developers.google.com/time/
推荐阅读
- swift - 访问和操作 EnvironmentObject 中的数组项
- c# - C#:一些机器抛出以下错误:无法转换类型为“Microsoft.Office.Interop.Excel.ApplicationClass”的 COM 对象
- mysql - MySQL:INNER JOIN 是否比使用 WHERE 子句的连接更优化使用?
- node.js - 在 node-cron 中多次启动完全相同的 node.js 脚本
- php - 在 php mysql 中使用 where 条件搜索输入数据
- java - 如何在 Android Studio 中使用 kotlin 将 onclick 侦听器设置为 Widget 中的 Button
- javascript - 将数据从谷歌电子表格保存到 javascript 可读变量
- python - 在解释器中工作和在终端中执行 Python 脚本时处理 __file__
- java - 创建一个正方形的二维数组
- neo4j - GraphQL & Neo4j:如何使用突变请求修改属性?