我正在将Google+登录添加到我的移动应用中。我为我的iOS应用
创建了一个新的客户ID(https://console.developers.google.com)根据文档(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 Node客户端(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);
}
});
我收到了#34; invalid_grant"
的回复服务器上的客户端ID是否与应用程序上的客户端ID相同?
任何想法?谢谢!
答案 0 :(得分: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);
}
});
}