Accessing Google oAuth giving invalid grant_type (

2019-09-19 06:15发布

I searched a lot in SO, skim through many questions regarding the same error, applied whatever they suggested, but nothing turned out. Hence writing here.

I am learning how to make a call to Google API (say Google Calendar API). I am going through the google developers tutorial from https://developers.google.com/identity/protocols/OAuth2ServiceAccount

So I have created a service account in the google, created credentials (I want to invoke Google API from my own application). After then I create JWT, singed my JWT with private key shared by google, and making a REST POST call to get the oAuth. Here is my code

public class TestGoogleAPI {

public static void main(String[] args) throws Exception{
    String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    long time = Calendar.getInstance().getTimeInMillis()/1000;

    String claimSet = "{\"iss\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com\"," +
                "\"scope\":\"https://www.googleapis.com/auth/calendar\"," +
                "\"aud\":\"https://www.googleapis.com/oauth2/v3/token\"," +
                "\"exp\":"+ (time+3600) +"," +
                "\"iat\":" + time +"}";


    String base64Header = new String(Base64.encodeBase64(header.getBytes()),"UTF-8");
    String base64ClaimSet = new String(Base64.encodeBase64(claimSet.getBytes()),"UTF-8");

    String input = base64Header + "." + base64ClaimSet;

    File f = new File("D:/downloads/privatekey.txt");
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int)f.length()];
    dis.readFully(keyBytes);
    dis.close();
    byte[] key = Base64.decodeBase64(keyBytes);

    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(key);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey privatekey =  kf.generatePrivate(spec);

    Signature signature = Signature.getInstance("SHA256withRSA"); 
    signature.initSign(privatekey);
    signature.update(input.getBytes());
    String base64Sign = new String(Base64.encodeBase64(signature.sign()),"UTF-8");

    doHttpPost("https://www.googleapis.com/oauth2/v3/token", input + "." + base64Sign);
}

public static void doHttpPost(String urlStr, String assertion) throws Exception{
    URL url = new URL(urlStr);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.setUseCaches(false);
      conn.setAllowUserInteraction(false);
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

      OutputStream out = conn.getOutputStream();
      Writer writer = new OutputStreamWriter(out, "UTF-8");
      writer.write("grant_type");
      writer.write("=");
      writer.write(URLEncoder.encode("urn:ietf:params:oauth:grant-type:jwt-bearer", "UTF-8"));
      writer.write("&");
      writer.write("assertion");
      writer.write("=");
      writer.write(URLEncoder.encode(assertion, "UTF-8"));
      writer.close();
      out.close();

      if (conn.getResponseCode() != 200) {
          System.out.println(conn.getResponseMessage());
      }

      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      StringBuilder sb = new StringBuilder();
      String line;
      while ((line = rd.readLine()) != null) {
        sb.append(line);
      }
      rd.close();

      conn.disconnect();
      System.out.println(sb.toString());
}

}

I am getting 400 (Bad request). I tried the same from "Chrome's Advanced Rest Client", but the result is same, invalid grant_type (Bad request).

{
   error: "invalid_grant"
   error_description: "Bad Request"
}

Am I missing any thing here. Please help me

Thanks

1条回答
戒情不戒烟
2楼-- · 2019-09-19 06:39

Finally I got the resolution. When I am encoding header and claimset, I am doing base64 encoding, instead of base64safeURL encoidng. After replacing

Base64.encodeBase64(some_data);

with

Base64.encodeBase64URLSafe(some_data);

at all occurrences in the above code, everything is working fine. I am getting the access token and able to hit the google API with oAuth token

查看更多
登录 后发表回答