伙计们,
我正在寻找一个使用com.google.api.client.auth.oauth2.draft10.AccessTokenRequest.ResourceOwnerPasswordCredentialsGrant
, 来验证用户而不使用基于 Web 的 UI的功能示例。尝试了课程中提供的示例(将https://server.example.com/authorize替换为https://accounts.google.com/o/oauth2/auth),但得到了 invalid_request 响应。这是发布到的正确 URL 吗?请求是否需要在其上设置其他属性?尝试像这样设置范围,但没有运气 request.set("scope", " https://www.googleapis.com/auth/calendar ")。还尝试设置 response_type,grant_type,任何帮助将不胜感激。这是代码(也附有maven项目):
测试.java
import com.google.api.client.auth.oauth2.draft10.AccessTokenErrorResponse;
import com.google.api.client.auth.oauth2.draft10.AccessTokenRequest.ResourceOwnerPasswordCredentialsGrant;
import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
public class Test {
public static void main(String[] args) throws Exception {
try {
ResourceOwnerPasswordCredentialsGrant request =
new ResourceOwnerPasswordCredentialsGrant(
new NetHttpTransport(),
new JacksonFactory(),
"https://accounts.google.com/o/oauth2/auth",
"<client_id>",
"<client_secret>",
"<user_username>",
"<user_password>");
AccessTokenResponse response = request.execute();
System.out.println("Access token: " + response.accessToken);
} catch (HttpResponseException e) {
AccessTokenErrorResponse response = e.response.parseAs(AccessTokenErrorResponse.class);
System.out.println("Error: " + response.error);
}
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.acme</groupId>
<artifactId>google-oauth</artifactId>
<version>1</version>
<name>Google OAuth</name>
<dependencies>
<dependency>
<groupId>com.google.api.client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.4.1-beta</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>