如何使用授权码授予类型(Java)进行苹果登录

huangapple 未分类评论45阅读模式
英文:

How to sign in with apple by the grant type of authorization_code (Java)

问题

以下是您提供的代码翻译后的内容:

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();
}

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)))
            .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;
}

请注意,这是您提供的代码的翻译部分,不包括问题或其他内容。如有需要,可以随时继续与我互动。

英文:

I have a issue that when the app send the identifityCode and authorization code to the app server, and I try to verify the code to apple server, but it always shows the error "invalid_client", here is my code:

public static String appleAuth(String authorizationCode) throws Exception {


        String token = generateJWT();
        HttpResponse&lt;String&gt; response = Unirest.post(APPLE_AUTH_URL)
                .header(HttpHeaders.CONTENT_TYPE, &quot;application/x-www-form-urlencoded&quot;)
                .header(HttpHeaders.USER_AGENT, &quot;my app&quot;)
                .field(&quot;client_id&quot;, CLIENT_ID)
                .field(&quot;client_secret&quot;, token)
                .field(&quot;grant_type&quot;, &quot;authorization_code&quot;)
                .field(&quot;code&quot;, authorizationCode)
                .asString();

        TokenResponse tokenResponse = new Gson().fromJson(response.getBody(), TokenResponse.class);
        String idToken = tokenResponse.getId_token();
        String payload = idToken.split(&quot;\\.&quot;)[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();
    }

to generate the JWT

private static String generateJWT() throws Exception {
        if (pKey == null) {
            pKey = getPrivateKey();
        }

        String token = Jwts.builder()
                .setHeaderParam(JwsHeader.ALGORITHM, &quot;ES256&quot;)
                .setHeaderParam(JwsHeader.KEY_ID, KEY_ID)
                .setIssuer(TEAM_ID)
                .setAudience(&quot;https://appleid.apple.com&quot;)
                .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;
    }

To get the private key

   private static PrivateKey getPrivateKey() throws Exception {
//read your key
        String path = new ClassPathResource(&quot;AuthKey_279SCN3AMY.p8&quot;).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;
    }

答案1

得分: 0

我相信你在使用颁发时间和过期时间时正在使用毫秒,然而Apple文档中指明需要使用秒。

其他部分看起来对我来说是正确的。

英文:

I believe you're using milliseconds for the issued at and expiry, when the Apple docs say seconds are required.

Everything else looks correct to me.

huangapple
  • 本文由 发表于 2020年4月10日 22:43:19
  • 转载请务必保留本文链接:https://java.coder-hub.com/61142696.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定