繁体   English   中英

如何通过授权类型的授权与苹果登录(Java)

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

我有一个问题,当应用程序将 identifityCode 和授权码发送到应用程序服务器时,我尝试向苹果服务器验证代码,但它总是显示错误“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;
    }

我相信当Apple 文档说需要秒时,您使用毫秒来表示和到期。

其他一切对我来说都是正确的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM