0

我在我的 iPad 应用程序中使用 Youtube Api。我设法使用 OAuth 2.0 进行身份验证并获取访问令牌。我的问题是令牌在一小时后过期,我不知道如何使用刷新令牌获取新令牌,而无需再次通过身份验证过程。我正在使用 XCode 4.5 和 iOS 5.1 & 6

4

2 回答 2

3

根据文档

如果您的应用程序在授权过程中获得了刷新令牌,那么您将需要定期使用该令牌来获取新的有效访问令牌。服务器端 Web 应用程序、已安装的应用程序和设备都获得刷新令牌。

因此,如果您已经拥有刷新令牌,则只需执行POST如下配置的请求

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

client_id=21302922996.apps.googleusercontent.com&
client_secret=<YOUR CLIENT SECRET>
refresh_token=<YOUR REFRESH TOKEN>
grant_type=refresh_token

你会得到一个回复​​,比如

{
  "access_token":<A NEW ACCESS TOKEN>,
  "expires_in":<AN EXPIRING TIME>,
  "token_type":"Bearer"
}
于 2013-01-02T14:33:06.517 回答
3

以下是使用 AFNetworking 刷新 accessToken 以发出请求的完整代码:

NSString *refreshToken = <YOUR_REFRESH_TOKEN>;

NSString *post = [NSString stringWithFormat:@"client_secret=%@&grant_type=refresh_token&refresh_token=%@&client_id=%@",kYouTubeClientSecret,refreshToken,kYouTubeClientID];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSURL *url = [NSURL URLWithString:@"https://accounts.google.com/o/oauth2/token"];

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

AFHTTPRequestOperation *httpRequest = [httpClient HTTPRequestOperationWithRequest:request
                                                                          success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                                                              NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
                                                                              NSString *newAccessToken = json[@"access_token"];
                                                                              NSLog(@"received new accessToken = %@",newAccessToken);

                                                                              // store accessToken here

                                                                          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                                                              NSLog(@"error refreshing token: %@",[error localizedDescription]);

                                                                          }];
[httpClient enqueueHTTPRequestOperation:httpRequest];
于 2013-05-22T22:33:32.070 回答