Google oauth 2.0刷新访问令牌

时间:2012-11-24 11:45:42

标签: iphone objective-c ios oauth

如何在Google Oauth 2.0中获取新的访问令牌?

我试过了:

    NSString * urlString1 = [NSString stringWithFormat:@"https://accounts.google.com/o/oauth2/token?client_id=my_client_id&client_secret=my_client_secret&refresh_token=%@&grant_type=refresh_token",auth.refreshToken];
    NSURL * url = [NSURL URLWithString:urlString1];   
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    NSURLConnection * connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    [connection start];

但结果是:方法不允许(错误405)

也许有另一种获取新访问令牌的方法?

请帮忙! 谢谢!

2 个答案:

答案 0 :(得分:0)

请使用以下代码在Google Plus中获取访问令牌

首先在 GTMOAuth2Authentication.h 文件中替换 - (NSString *)description 方法,您一定会获得G + Acccess令牌

 - (NSString *)description 
 {
        NSArray *props = [NSArray arrayWithObjects:@"accessToken",nil];//[NSArray arrayWithObjects:@"accessToken", @"refreshToken",@"code", @"assertion", @"expirationDate", @"errorString",nil];
       NSMutableString *valuesStr = [NSMutableString string];
       NSString *separator = @"";
       for (NSString *prop in props) {
       id result = [self valueForKey:prop];
       if (result)
       {
          [valuesStr appendFormat:@"%@",result];
          separator = @", ";
      }
    }

 return [NSString stringWithFormat:@"%@",valuesStr];
}
.h文件中的

@class GPPSignInButton;
@interface GPlusView : UIViewController <GPPSignInDelegate>
{
      IBOutlet GPPSignInButton *signInButton;
}

@property (retain, nonatomic) IBOutlet GPPSignInButton *signInButton;
.m文件中的

 signInButton_.shouldFetchGoogleUserEmail = TRUE;
 signInButton_.delegate = self;

 signInButton_.clientID = [SamacharAppDelegate clientID];
 signInButton_.scope = [NSArray arrayWithObjects:
                       @"https://www.googleapis.com/auth/plus.me",
                       nil];


 -(void)finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error
 {
     if (error) {
           NSLog(@"Error = %@",error.localizedDescription);
           return;
     }
     NSLog("Auth Data = %@",auth);

   /* Auth Data =  {accessToken="ya29.AHES6ZQYLmSBc9n4pLj9U8OQrFoTDZnGLH8okPkxbda7B0Q", refreshToken="1/puItTB-sqHupfp9qPCKcb6_gWUjgcxwzc9TKJvUwMEI", expirationDate="2012-11-24 13:30:55 +0000"}  */

}

答案 1 :(得分:0)

HTTP 405意味着您正在尝试使用资源不允许的动词。例如,在只读POST资源上使用GET或在只接受PUT s的写入资源上使用POST

请参阅abraham's answerGoogle with oauth 2