如何在iOS中使用GIDSignIn和GTMOAuth2Authentication获取刷新令牌?

hjo*_*ard 8 youtube-api ios oauth-2.0 google-plus

我正在编写一个iOS应用程序,它使用Google的GIDSignIn [1]登录用户,GTLServiceYoutube对Youtube执行查询(上传视频和检索Youtube视频列表).

这在用户首次登录时工作正常,但大约一小时后,访问令牌过期,用户由于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];
}
Run Code Online (Sandbox Code Playgroud)

哪里[[UserManager sharedInstance].youTubeService是GTLServiceYouTube的一个实例.

唯一的问题是GTLServiceYouTube.GIDSignIn似乎处理刷新令牌,因此用户始终在首次登录后登录.但GTLOAuth2Authentication仅在首次登录时有效,并在一小时后中断.

所以我的问题是:我在这里做错了吗?或者我在刷新后遗漏了一些东西以获得GTMOAuth2Authentication中的正确访问令牌?

[1] https://developers.google.com/identity/sign-in/ios/api/interface_g_i_d_sign_in

JAL*_*JAL 0

您可以使用GTMOAuth2Authentication该方法强制刷新身份验证令牌authorizeRequest:

来自 GTMOAuth2Authentication.h

// The request argument may be nil to just force a refresh of the access token,
// if needed.

- (void)authorizeRequest:(NSMutableURLRequest *)request
       completionHandler:(void (^)(NSError *error))handler;
Run Code Online (Sandbox Code Playgroud)

执行:

// In your sign in method
[[GPPSignIn sharedInstance] setKeychainName:@"googleAuth"];

// ...

// Retrieving auth and refreshing token
GTMOAuth2Authentication *auth;
auth = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:@"googleAuth"
                                                             clientID:@"kYourGoogleClientId"
                                                         clientSecret:@"kYourGoogleClientSecret"];

NSLog(@"old auth: %@", auth);

[auth authorizeRequest:nil completionHandler:^(NSError *error) {
    if (error) {
        // no auth data or refresh failed
        NSLog(@"Error: %@", error);
    } else {
        // Auth token refresh successful
        NSLog(@"new auth: %@", auth);
    }
}];
Run Code Online (Sandbox Code Playgroud)

  • 问题是我使用的是 GIDSignIn 而不是 GPPSignIn 并且 GIDSignIn 没有 setKeychainName 方法。你知道如何用 GIDSignIn 做同样的事情吗? (2认同)