据苹果公司称doc为了验证 Apple 的授权码,我们需要 POST 到http://appleid.apple.com/auth/token使用这个参数:
#!java
token = generateJWT(keyId, teamId, clientId, certificatePath);
HttpResponse<String> response = Unirest.post(authUrl)
.header("Content-Type", "application/x-www-form-urlencoded")
.field("client_id", clientId)
.field("client_secret", token)
.field("grant_type", "authorization_code")
.field("code", authorizationCode)
.asString();
where:
#!java
private static String generateJWT(String keyId, String teamId, String clientId, String certificatePath) throws Exception {
if (pKey == null) {
pKey = getPrivateKey(certificatePath);
}
return Jwts.builder()
.setHeaderParam(JwsHeader.KEY_ID, keyId)
.setIssuer(teamId)
.setAudience("https://appleid.apple.com")
.setSubject(clientId)
.setExpiration(new Date(System.currentTimeMillis() + (1000 * 60 * 5)))
.setIssuedAt(new Date(System.currentTimeMillis()))
.signWith(pKey, SignatureAlgorithm.ES256)
.compact();
}
private static PrivateKey getPrivateKey(String certificatePath) throws Exception {
//read your key
try (PEMParser pemParser = new PEMParser(new FileReader(certificatePath))) {
final JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
final PrivateKeyInfo object = (PrivateKeyInfo) pemParser.readObject();
final PrivateKey pKey = converter.getPrivateKey(object);
return pKey;
}
}
我们检查 JWT 包含苹果所需的所有字段:
#!json
{
"alg": "ES256",
"typ": "JWT",
"kid": "6876D87D6"
}
{
"iat": 1578654031,
"exp": 1578740431,
"aud": "https://appleid.apple.com",
"iss": "57675576576",
"sub": "com.blahblah.client"
}
但这就是问题所在。它总是返回 400 HTTP 错误并带有以下正文:
#!json
{"error":"invalid_grant"}
从这里我们完全迷失了。我们不明白为什么代码不正确或者为什么它有 invalid_grant 错误。