我是使用oauth 2.0的新手,所以我按照谷歌的教程使用oauth 2.0访问Google Analytics 我在google开发人员控制台中创建了一个OAuth客户端,并使用此代码访问分析:
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
// authorization
Credential credential = authorize();
// set up global Oauth2 instance
oauth2 =
new Oauth2.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(
APPLICATION_NAME).build();
Analytics analytics = new Analytics.Builder(httpTransport, JSON_FACTORY, credential).build();
授权方法:
private static Credential authorize() throws Exception
{
// load client secrets
clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(OAuth2Sample.class.getResourceAsStream("/client_secrets.json")));
if (clientSecrets.getDetails().getClientId().startsWith("Enter") || clientSecrets.getDetails().getClientSecret().startsWith("Enter "))
{
System.out.println("Enter Client ID and Secret from https://code.google.com/apis/console/ "
+ "into oauth2-cmdline-sample/src/main/resources/client_secrets.json");
System.exit(1);
}
// set up authorization code flow
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(dataStoreFactory).build();
// authorize
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("[my email]");
}
我从我在Google开发者控制台中创建的Auth 2.0客户端下载JSON文件:
{
"installed":
{"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"client_secret":[my clients secret],
"token_uri":"https://accounts.google.com/o/oauth2/token",
"redirect_uris":["urn:ietf:wg:oauth:2.0:oob","oob"],
"client_id": [my client id],
"auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs"
}
}
我使用了代码,结果是:
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_grant"
}
你知道我遗失了什么吗? 非常感谢你的帮助!