通过Keychain检索access_token的GTM OAuth2未成功

时间:2012-08-22 14:02:38

标签: iphone cocoa-touch oauth-2.0

我正在关注如何授权应用访问一个或多个API的Google示例。 问题是,当我成功授权我获得access_token,但在此之后,我无法从钥匙串中获取它,它被存储到。我在某处读到iPhone模拟器不能与钥匙串一起使用,是不是因为它,如果可以的话,你可以告诉我其他一些方法来存储我的访问令牌吗?

这是我的代码:

    static NSString *const kKeychainItemName = @"OAuthGoogleReader";

    GTMOAuth2Authentication *auth;
    auth = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
                                                                 clientID:kClientID
                                                             clientSecret:kClientSecret];

BOOL isSignedIn = [auth canAuthorize];
    if (isSignedIn) {
        NSLog(@"Signed");
        self.window.rootViewController = self.viewController;
        auth.accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
          NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/reader/api/0/subscription/list?access_token=%@", [auth accessToken]]]];
          GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request];

          // optional upload body data

          //[myFetcher setPostData:[postString dataUsingEncoding:NSUTF8StringEncoding]];
        [myFetcher setAuthorizer:auth];
          [myFetcher beginFetchWithDelegate:self
                          didFinishSelector:@selector(myFetcher:finishedWithData:error:)];
         // - (void)myFetcher:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)retrievedData error:(NSError *)error;
    }else{
    NSString *scope = @"https://www.google.com/reader/api/";

    GTMOAuth2ViewControllerTouch *viewController;
    viewController = [[GTMOAuth2ViewControllerTouch alloc] initWithScope:scope
                                                                clientID:kClientID
                                                            clientSecret:kClientSecret
                                                        keychainItemName:kKeychainItemName
                                                                delegate:self
                                                        finishedSelector:@selector(viewController:finishedWithAuth:error:)];

        self.window.rootViewController = viewController;
    }

我收到错误:

2012-08-22 16:54:47.253 greader[20833:c07] Signed
2012-08-22 16:54:47.705 greader[20833:c07] Cannot authorize request with scheme http (<NSMutableURLRequest http://www.google.com/reader/api/0/subscription/list?access_token=(null)>)

你可以看到access_token只是零。

另外一些关于如何使用这个库的简单例子会很棒。

谢谢!

1 个答案:

答案 0 :(得分:1)

gtm-oauth2库处理在钥匙串上存储和检索访问令牌和其他auth值。应用程序不需要直接使用访问令牌字符串,应用程序也不应该将授权令牌放入NSUserDefaults,因为这不够安全。

默认情况下,

gtm-auth2将拒绝将访问令牌附加到具有http:scheme的URL。只有与https:scheme URL一起使用时,OAuth 2才是安全的。