0

iPad アプリケーションで Youtube Api を使用しています。OAuth 2.0 を使用して認証を取得し、アクセス トークンを取得することができました。私の問題は、トークンが 1 時間後に期限切れになり、認証プロセスを再度実行せずに更新トークンを使用して新しいトークンを取得する方法がわからないことです。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 に答える