我正在编写一个 iOS 应用程序,它使用 Google 的 GIDSignIn [1] 来登录用户并使用 GTLServiceYoutube 来执行针对 Youtube 的查询(上传视频和检索 Youtube 视频列表)。
这在用户首次登录时工作正常,但大约一小时后,访问 token 过期并且由于 401 错误(无效凭据),用户无法再使用 GTLServiceYoutube 执行查询。
成功登录后,我使用以下代码设置 GTMOAuth2Authentication:
- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)error {
if (error == nil) {
[self setAuthorizerForSignIn:signIn user:user];
}
[super signIn:signIn didSignInForUser:user withError:error];
}
- (void)setAuthorizerForSignIn:(GIDSignIn *)signIn user:(GIDGoogleUser *)user {
GTMOAuth2Authentication *auth = [[GTMOAuth2Authentication alloc] init];
[auth setClientID:signIn.clientID];
[auth setClientSecret:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"GoogleClientSecret"]];
[auth setUserEmail:user.profile.email];
[auth setUserID:user.userID];
[auth setAccessToken:user.authentication.accessToken];
[auth setRefreshToken:user.authentication.refreshToken];
[auth setExpirationDate: user.authentication.accessTokenExpirationDate];
[[UserManager sharedInstance].youTubeService setAuthorizer:auth];
}
其中 [[UserManager sharedInstance].youTubeService
是 GTLServiceYouTube 的一个实例。
唯一的问题是 GTLServiceYouTube。 GIDSignIn 似乎处理刷新 token ,以便用户在首次登录后始终登录。但 GTLOAuth2Authentication 仅在第一次登录时有效,一小时后失效。
所以我的问题是:我在这里做错了什么吗?或者我是否遗漏了刷新后在 GTMOAuth2Authentication 中获取正确访问 token 的内容?
[1] https://developers.google.com/identity/sign-in/ios/api/interface_g_i_d_sign_in
最佳答案
我认为执行此操作的正确方法是在重新打开应用程序或需要刷新 token 时让用户重新登录。这可以通过调用 [[GIDSignIn sharedInstance] signInSilently]
来完成,然后在完成登录时使用新的身份验证 token 更新钥匙串(keychain)或数据存储。
关于ios - 如何在 iOS 中使用 GIDSignIn 和 GTMOAuth2Authentication 获取刷新 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30522519/