如何在Google OAuth中使用资源所有者密码凭据?

时间:2012-11-27 18:25:05

标签: java oauth-2.0 google-oauth

民间,

我正在寻找使用com.google.api.client.auth.oauth2.draft10.AccessTokenRequest.ResourceOwnerPasswordCredentialsGrant的功能示例,在不使用基于Web的用户界面的情况下对用户进行身份验证。尝试了类中提供的示例(将https://server.example.com/authorize替换为https://accounts.google.com/o/oauth2/auth),但获得了invalid_request响应。这是发布到的正确URL吗?请求是否需要设置其他属性?尝试这样的设置范围,但没有运气request.set(“范围”,“https://www.googleapis.com/auth/calendar”)。还尝试设置response_type,grant_type,任何帮助将不胜感激。这是代码(maven项目也附加):

Test.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>

1 个答案:

答案 0 :(得分:1)

Google OAuth2.0授权服务器不支持资源所有者密码凭据流。如果您提供避免基于Web的UI的原因,可能会有一些可用的解决方法 - 例如,企业设置中的service accounts,您的应用可以代表用户执行此操作。