使用 Java 从 Google 请求 OAUTH 的 JWT 签名无效

Posted

技术标签:

【中文标题】使用 Java 从 Google 请求 OAUTH 的 JWT 签名无效【英文标题】:Invalid JWT Signature requesting OAUTH from Google using Java 【发布时间】:2020-12-07 13:27:48 【问题描述】:

我正在尝试按照here 的指示构建正确的 JWT 请求以向 Google 抛出以获取临时 oauth 令牌,以便我可以查询 Google Sheets API。我意识到有一个可以使用的 Java 库,但我想了解这个过程。我的签名似乎有问题,因为我得到的回复是......


  "error": "invalid_grant",
  "error_description": "Invalid JWT Signature."

这是我正在尝试以 Groovy 形式执行的操作...

String JWT_HEADER = "\"alg\":\"RS256\",\"typ\":\"JWT\"";
String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";

String jwtHeaderBase64 = Base64.getEncoder().encodeToString( JWT_HEADER.getBytes() );

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
long secondsSinceEpoch = calendar.getTimeInMillis() / 1000L;

VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.init();
Template claimSetTemplate = velocityEngine.getTemplate("jwt-claim-set.json");
/*  looks like ...

  "iss": "<GOOGLE_SERVICE_ACCOUNT_EMAIL>",
  "scope": "https://www.googleapis.com/auth/spreadsheets",
  "aud": "https://oauth2.googleapis.com/token",
  "exp": $EXPIRATION_UNIX_TIME,
  "iat": $CREATION_UNIX_TIME

*/
VelocityContext context = new VelocityContext();
context.put( "EXPIRATION_UNIX_TIME", Long.toString( secondsSinceEpoch + 3600 ) );
context.put( "CREATION_UNIX_TIME", Long.toString( secondsSinceEpoch) );
StringWriter writer = new StringWriter();
claimSetTemplate.merge( context, writer );
String claimSetJson = writer.toString();
println( "jwt-claim-set:\n\n" + claimSetJson );

String claimSetJsonBase64 = Base64.getEncoder().encodeToString( claimSetJson.getBytes() );
println( "base64 claim set: " + claimSetJsonBase64 );

String baseString = jwtHeaderBase64 + "." + claimSetJsonBase64;

JsonParser jsonParser = new JsonParser();
JsonElement rootJsonElement = jsonParser.parse( new FileReader( new File( "gserviceaccount-client-secret.json" ) ) );
JsonPrimitive privateKeyJsonPrimitive = rootJsonElement.getAsJsonPrimitive( "private_key" );
String privateKey = privateKeyJsonPrimitive.getAsString();
privateKey = privateKey.replaceAll("-----END PRIVATE KEY-----", "")
                      .replaceAll("-----BEGIN PRIVATE KEY-----", "")
                      .replaceAll("\n", "");

byte[] decodedPrivateKeyBytes = Base64.getDecoder().decode( privateKey );
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec( decodedPrivateKeyBytes );
Signature privateSignature = Signature.getInstance( "SHA256withRSA" );
KeyFactory keyFactory = KeyFactory.getInstance( "RSA" );
privateSignature.initSign( keyFactory.generatePrivate( keySpec ) );
privateSignature.update( baseString.getBytes( "UTF-8" ) );
byte[] signatureBytes = privateSignature.sign();
String signature = new String( signatureBytes );
String signatureBase64 = Base64.getEncoder().encodeToString( signature.getBytes() );
println( "base64 signature: " + signatureBase64 );

String jwt = jwtHeaderBase64 + "." + claimSetJsonBase64 + "." + signatureBase64;

String url = "https://oauth2.googleapis.com/token";
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost( url );
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("grant_type", GRANT_TYPE));
postParameters.add(new BasicNameValuePair("assertion", jwt));
request.setEntity( new UrlEncodedFormEntity( postParameters, "UTF-8" ) );
HttpResponse response = client.execute( request );

StatusLine status = response.getStatusLine();
HttpEntity responseEntity = response.getEntity();

String content = "";
if (responseEntity) 
  content = EntityUtils.toString(responseEntity);


if (status.getStatusCode() > 204 ) 
  println("HTTPCODE " + status.getStatusCode() + " from " + url);
  println( content );


JsonObject responseJsonObject = null;
if (content.length() > 0) 
  JsonElement jsonElement = new JsonParser().parse(content);
  // If an object, return it
  if (jsonElement instanceof JsonObject) 
    responseJsonObject = jsonElement.getAsJsonObject();
  
  // If an array, return the first item
  else if (jsonElement instanceof JsonArray) 
    JsonArray array = jsonElement.getAsJsonArray()
    responseJsonObject = array.get(0)
  


Gson gson = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gson.toJson( responseJsonObject );
println( prettyJson );

【问题讨论】:

【参考方案1】:

我让它工作了。签名的编码似乎是错误的。我把它改成:

byte[] signatureBytes = privateSignature.sign();
String signature = Base64.getEncoder().encodeToString(signatureBytes);
println( "signature: " + signature );
String jwt = jwtHeaderBase64 + "." + claimSetJsonBase64 + "." + signature;

现在我得到了返回的有效访问令牌

【讨论】:

以上是关于使用 Java 从 Google 请求 OAUTH 的 JWT 签名无效的主要内容,如果未能解决你的问题,请参考以下文章

Google OAuth Java 客户端和 Twitter API

Google API OAuth2.0 JWT 返回 400 - 错误请求

使用新 oAuth 1.0 的 Google Ads API、C#、SOAP 请求?

未找到 Google 云打印 OAuth 范围

Google OAuth 在不请求的情况下返回其他范围

使用 google-api-java-oauth 的 oauth1 示例 [关闭]