У меня проблема с тем, что, когда приложение отправляет код идентификации и код авторизации на сервер приложений, и я пытаюсь проверить код на сервер Apple, но всегда отображается ошибка «invalid_client», вот мой код:
public static String appleAuth(String authorizationCode) throws Exception {
String token = generateJWT();
HttpResponse<String> response = Unirest.post(APPLE_AUTH_URL)
.header(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(HttpHeaders.USER_AGENT, "my app")
.field("client_id", CLIENT_ID)
.field("client_secret", token)
.field("grant_type", "authorization_code")
.field("code", authorizationCode)
.asString();
TokenResponse tokenResponse = new Gson().fromJson(response.getBody(), TokenResponse.class);
String idToken = tokenResponse.getId_token();
String payload = idToken.split("\\.")[1];//0 is header we ignore it for now
String decoded = new String(Decoders.BASE64.decode(payload));
IdTokenPayload idTokenPayload = new Gson().fromJson(decoded, IdTokenPayload.class);
return idTokenPayload.getSub();
}
для генерации JWT
private static String generateJWT() throws Exception {
if (pKey == null) {
pKey = getPrivateKey();
}
String token = Jwts.builder()
.setHeaderParam(JwsHeader.ALGORITHM, "ES256")
.setHeaderParam(JwsHeader.KEY_ID, KEY_ID)
.setIssuer(TEAM_ID)
.setAudience("https://appleid.apple.com")
.setSubject(CLIENT_ID)
.setExpiration(new Date(System.currentTimeMillis() + (1000 * 60 * 60 * 24 * 5)))
.setIssuedAt(new Date(System.currentTimeMillis()- (1000 * 60 * 60 * 24 * 2)))
//.setExpiration(new Date(Date.from(Instant.EPOCH).getTime() + (1000 * 60 * 60 * 24 * 2)))
//.setIssuedAt(new Date(Date.from(Instant.EPOCH).getTime() - (1000 * 60 * 60 * 24 * 1)))
// .setNotBefore(new Date(System.currentTimeMillis()- (1000 * 60 * 60 * 24 * 2)))
.signWith(SignatureAlgorithm.ES256, pKey)
.compact();
return token;
}
Для получения закрытого ключа
private static PrivateKey getPrivateKey() throws Exception {
//read your key
String path = new ClassPathResource("AuthKey_279SCN3AMY.p8").getFile().getAbsolutePath();
final PEMParser pemParser = new PEMParser(new FileReader(path));
final JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
final PrivateKeyInfo object = (PrivateKeyInfo) pemParser.readObject();
final PrivateKey pKey = converter.getPrivateKey(object);
return pKey;
}