2014-08-19 3 views
0

Я добавляю Google+ в свои мобильные приложения. Я создал новый идентификатор клиента (https://console.developers.google.com) для моего IOS приложения Client ID for iOS AppGoogle API Недействительный код авторизации Exchange для токена доступа и обновления

Согласно документации (https://developers.google.com/+/mobile/ios/sign-in#enable_server-side_api_access_for_your_app)

«Для того, чтобы получить маркер доступа и обновить маркер для вашего сервера, вы можете запросить одноцветный который ваш сервер обменивает на эти два токена ».

#pragma mark - GPPSignInDelegate Methods 

- (void)finishedWithAuth: (GTMOAuth2Authentication *)auth error: (NSError *) error 
{ 
    if (error) { 
     NSLog(@"%@", error); 
    } else { 
     NSString *serverCode = [GPPSignIn sharedInstance].homeServerAuthorizationCode; 

     if (serverCode) { 
      [[AFHTTPSessionManager manager] POST:@"http://localhost:3000/user/connect/google" 
             parameters:@{@"device": [[[UIDevice currentDevice] identifierForVendor] UUIDString], 
                @"account": @"google", 
                @"info": serverCode} 
             success:^(NSURLSessionDataTask *task, id responseObject) { 
              NSLog(@"Google+ Reponse: %@", responseObject); 
             } failure:^(NSURLSessionDataTask *task, NSError *error) { 
              NSLog(@"%@", error); 
             }]; 
     } 
    } 
} 

Я использую Nodejs и Google API узла клиента (https://github.com/google/google-api-nodejs-client/) на стороне сервера.

var google = require('googleapis'); 
var OAuth2 = google.auth.OAuth2; 

var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL); 
var scopes = [ 'https://www.googleapis.com/auth/plus.me' ]; 

oauth2Client.getToken('the token from ios', function(err, tokens) { 
    if (err) { 
     console.log(err); 
    } else { 
     console.log(tokens); 
     oauth2Client.setCredentials(tokens); 
    } 
}); 

я получаю ответ «invalid_grant»

является идентификатор клиента на сервере же на идентификатора клиента на приложение?

любые идеи? благодаря!

+0

вы пытаетесь на новый GooglePlus SDK? – Kittu

+0

yup. используя последнюю версию npm googleapis – YarGnawh

+0

В коде Node.js, где находится «код авторизации»? –

ответ

0

После того, как у меня есть код авторизации, это работает для меня, чтобы обменять его:

// See https://github.com/request/request 
var request = require('request'); 

/* For documentation on HTTP/REST means of doing this authorization code exchange, see https://developers.google.com/identity/protocols/OAuth2WebServer 
    POST /oauth2/v3/token HTTP/1.1 
    Host: www.googleapis.com 
    Content-Type: application/x-www-form-urlencoded 

    code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7& 
    client_id=8819981768.apps.googleusercontent.com& 
    client_secret={client_secret}& 
    redirect_uri=https://oauth2-login-demo.appspot.com/code& 
    grant_type=authorization_code 

Here's an example of what I get back: 

{ 
"access_token":<snip>, 
"token_type": "Bearer", 
"expires_in": 3600, 
"refresh_token": <snip>, 
"id_token": <snip> 
} 
*/ 
// The callback has two parameters: error, and the if error is null, an instance of the above json structure. 
function exchangeAuthorizationCode(authorizationCode, clientId, clientSecret, callback) { 
    var args = 
     {url:'https://www.googleapis.com/oauth2/v3/token', 
     form: {code: authorizationCode, 
       client_id: clientId, 
       client_secret: clientSecret, 
       grant_type: "authorization_code" 
       } 
     } 

    request.post(args, function(error, httpResponse, body) { 
     if (!error && httpResponse.statusCode == 200) { 
      callback(null, JSON.parse(body)); 
     } else { 
      callback(error, null); 
     } 
    }); 
} 
Смежные вопросы