Reputation: 943
I am using the Youtube Api in my iPad application. i managed to get authenticated and get the access token using the OAuth 2.0. my problem is that the token expires after one hour and i don't know how to get a new one using the refresh-token without going through the authentication process again. i am using XCode 4.5 and iOS 5.1 & 6
Upvotes: 0
Views: 4521
Reputation: 1126
Here is the full code to refresh the accessToken using AFNetworking to make the request:
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];
Upvotes: 3
Reputation: 108159
According do the documentation
If your application obtains a refresh token during the authorization process, then you will need to periodically use that token to obtain a new, valid access token. Server-side web applications, installed applications, and devices all obtain refresh tokens.
So if you already have your refresh token, you just need to perform a POST
request configured as follows
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
and you'll get back a response like
{
"access_token":<A NEW ACCESS TOKEN>,
"expires_in":<AN EXPIRING TIME>,
"token_type":"Bearer"
}
Upvotes: 3