两足oauth2:如何在没有特定API库的情况下调用Google Drive Rest API

时间:2018-08-16 18:51:49

标签: google-api google-oauth google-api-java-client

我已经在Google Developer's Console中创建了一个应用,然后创建了OAuth2凭据。我有一个 client_id client_secret 。现在,我想使用它们来获取访问令牌,以两脚调用Google Drive API。我在Java中使用Google的oauth2客户端:

import com.google.api.client.auth.oauth2.ClientCredentialsTokenRequest;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
import com.google.api.client.auth.oauth2.TokenResponse;
...
public void oauth2Test() {
   String clientId = "...";
   String clientSecret = "...";
   ClientCredentialsTokenRequest request = new ClientCredentialsTokenRequest(
         new NetHttpTransport(),
         new JacksonFactory(),
         new GenericUrl("https://accounts.google.com/o/oauth2/auth"));
   request.setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret));
   TokenResponse response;
   try {
      response = request.execute();      
   } catch (Exception ex) {
      ex.printStackTrace();
   }
}

但是,我收到一条带有消息的“ 400错误请求”

  

“缺少必需的参数:response_type”。

在两条腿的请求模型中获取访问令牌的正确方法是什么?注意:我只有 client_id client_secret ,我没有完整的API令牌。

编辑:我最初的问题是不精确的。虽然我更喜欢仅从client_id和client_secret开始,但这不是必需的。可以使用Google特定的API来获取访问令牌,也可以使用GoogleCredential。 必要是,我能够使用从一般REST调用中的授权过程中获得的任何访问令牌。换句话说,给定Google应用程序凭据(可以为{client_id,client_secret}或JSON或P12格式的Google服务帐户密钥),如何获取访问令牌以及如何在REST API调用中使用它们-我要设置授权标头还是其他?

第一个答案指出不支持client_credential,我已经验证了这一点。但是我仍然需要获取承载令牌的路径,以便可以在没有特定Google客户端API库的REST调用中使用它。因此,我从有效的代码开始,但是使用了Google库。它需要一个JSON凭证文件。

InputStream is = getClass().getResourceAsStream("JSONCredFile");
GoogleCredential credential = GoogleCredential.fromStream(is).createScoped(scopes);
Drive service = new Drive.Builder(new NetHttpTransport(), new JacksonFactory(), credential)
        .setApplicationName("My app")
        .build();
FileList result = service.files().list().setPageSize(10)
        .setFields("nextPageToken, files(id, name)")
        .execute();

通过将SSLSocket代理连接到凭据(详细信息省略),我能够跟踪出站通信:

POST /token HTTP/1.1
Accept-Encoding: gzip
User-Agent: Google-HTTP-Java-Client/1.23.0 (gzip)
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: oauth2.googleapis.com
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
Content-Length: 771

grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=<lots of encoded stuff>

回复是一个gzip编码的承载令牌,该令牌在API调用中使用:

GET /drive/v3/files?fields=nextPageToken,%20files(id,%20name)&pageSize=10 HTTP/1.1
Accept-Encoding: gzip
Authorization: Bearer ya29.c.Eln_BSgrx0afa85mdMstW5jzEvM5dotWpctSXl-DE1jeO2mmu1h0FErr_EZO05YnC-B1yz30IBwOyFXoWr_wwKxlZk08R6eZldNU-EAfrQ1yNftymn_Qqc_pfg

很明显,这是JWT profile of oauth2。但是现在呢?我需要以某种方式获取承载令牌,而无需实际通过特定库进行API调用。 Google OAuth2库似乎不支持此请求类型,至少我看不到TokenRequest的“ JWT”风格。我可以直接编写OAuth2调用,还是创建支持JWT的TokenRequest的子类?

还有更好的主意吗?

2 个答案:

答案 0 :(得分:0)

Google不支持grant_type = client_credentials,这是使用OAuth客户端ID和密码进行2LO的方式。

您可以使用服务帐户执行2LO:https://developers.google.com/identity/protocols/OAuth2ServiceAccount

答案 1 :(得分:0)

好的,我终于弄清楚了如何制作JWT,发送OAuth2请求以及提取访问令牌。为了更轻松地与Google OAuth2客户端集成,我将TokenRequest子类化:

import com.google.api.client.auth.oauth2.TokenRequest;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.Collection;
import java.util.stream.Collectors;
import org.joda.time.DateTime;

/**
 * @author jlilley
 */
public class JWTTokenRequest extends TokenRequest {
    private String serviceKeyJson;
    private boolean doRsa = true;
    public JWTTokenRequest(HttpTransport transport, JsonFactory jsonFactory, GenericUrl tokenServerUrl) {
        super(transport, jsonFactory, tokenServerUrl, "urn:ietf:params:oauth:grant-type:jwt-bearer");
    }
    @Override
    public JWTTokenRequest setTokenServerUrl(GenericUrl tokenServerUrl) {
        return (JWTTokenRequest)super.setTokenServerUrl(tokenServerUrl);
    }
    public JWTTokenRequest setServiceKey(String json) throws Exception {
        this.serviceKeyJson = json;
        return this;
    }
    public JWTTokenRequest setServiceKey(InputStream is) throws Exception {
        try (BufferedReader buffer = new BufferedReader(new InputStreamReader(is))) {
            return setServiceKey(buffer.lines().collect(Collectors.joining("\n")));
        }
    }
    @Override
    public JWTTokenRequest setScopes(Collection<String> scopes) {
        return (JWTTokenRequest) super.setScopes(scopes);
    }
    @Override
    public JWTTokenRequest set(String fieldName, Object value) {
        return (JWTTokenRequest) super.set(fieldName, value);
    }    
    /**
     * Create a JWT for the given project id, signed with the given RSA key.
     */
    private String signJwtRsa(JwtBuilder jwtBuilder, PKCS8EncodedKeySpec spec) {
        try {
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
        } catch (Exception ex) {
            throw new RuntimeException("Error signing JWT", ex);
        }
    }

    /**
     * Create a JWT for the given project id, signed with the given ES key.
     */
    private String signJwtEs(JwtBuilder jwtBuilder, PKCS8EncodedKeySpec spec) {
        try {
            KeyFactory kf = KeyFactory.getInstance("EC");
            return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact();
        } catch (Exception ex) {
            throw new RuntimeException("Error signing JWT", ex);
        }
    }

    /**
     * Finalize the JWT and set it in the assertion property of the web service call
     * @throws java.io.IOException
     */
    void makeAssertion() {
        JsonParser parser = new JsonParser();
        JsonObject jsonDoc = (JsonObject) parser.parse(serviceKeyJson);
        String pkStr = jsonDoc.get("private_key").getAsString()
                .replace("\n", "")
                .replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "");
        byte[] pkBytes = Base64.getDecoder().decode(pkStr);
        DateTime now = new DateTime();
        JwtBuilder jwtBuilder = Jwts.builder()
                .setIssuedAt(now.toDate())
                .setExpiration(now.plusMinutes(60).toDate())
                .setAudience(getTokenServerUrl().toString())
                .setIssuer(jsonDoc.get("client_email").getAsString());
        if (getScopes() != null) {
            jwtBuilder = jwtBuilder.claim("scope", getScopes());
        }
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pkBytes);
        String pkId = jsonDoc.get("private_key_id").getAsString();
        jwtBuilder.setHeaderParam("kid", pkId);
        jwtBuilder.setHeaderParam("typ", "JWT");
        set("assertion", doRsa ? signJwtRsa(jwtBuilder, spec) : signJwtEs(jwtBuilder, spec));
    }

    /**
     * Finalize the JWT, set it in the assertion property of the web service call, and make the token request.
     */
    @Override
    public TokenResponse execute() throws IOException {
        makeAssertion();
        return super.execute();
    }
}

为此,我可以从服务帐户JSON密钥文件中设置令牌请求,然后执行execute()并获取生成的访问令牌。请注意,令牌续订责任由调用者承担。