使用java从google请求oauth的jwt签名无效

mwkjh3gx  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(442)

我正试图按照这里的说明构造一个正确的jwt请求来抛出google以获得一个临时oauth令牌,这样我就可以查询googlesheetsapi了。我知道有一个java库可以使用,但我想了解这个过程。似乎我的签名有问题,因为我得到的答复是。。。

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

下面是我想用非常棒的方式做的。。。

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 );
2sbarzqh

2sbarzqh1#

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

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

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

相关问题