java 后端 sign in with apple 隨筆

一、前言

本文旨在總結sign in with apple 遇到的一些問題。

二、方案

  • 目的是驗證前端傳來的授權碼和apple user是否匹配。方案采用使用私鑰生成token的方式。需要公鑰驗證的,可以查看下方參考文獻1。

三、過程

1.接口以及對Required參數(shù)的具體分析

https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens

  • client_id是蘋果控臺設置的包名,前后端一致的,找產(chǎn)品要即可;
  • code 前端傳的授權碼(ps:只能使用一次,用過一次后過期,過期返回值{"error":"invalid_grant"});
  • grant_type 此處傳authorization_code字符串即可;
  • client_secret需要處理。

2.生成client_secret

官方文檔最下方有具體生成步驟,覺得我下面講的不清楚的可以自行查看。

(1)需要參數(shù)client_id,kid,teamIdprivate keyclient_id就是上面提到的包名字符串,重點說一下后面幾個參數(shù)。
  • kid:把https://help.apple.com/developer-account/#/dev77c875b7e
    這個鏈接丟給產(chǎn)品經(jīng)理(本人實在沒圖,更具體點可以參考下方參考文獻2)
  • teamId 也是在上一步中生成的,private App Id格式是xxxxxxxxxx.com.abcd.lalala,第一個‘.’前面的10位就是需要的teamId;
  • private key也是按照上面文檔生成的,是一個.p8文件,我們把它后綴改成.txt取其中的字符串即可;
    獲取到的private key
(2)生成client_secret
  • 經(jīng)測試auth0-jwt和jjwt都可以,demo給的是auth0的sign
  • 依賴:
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.10.3</version>
        </dependency>
  • 代碼:
    public static final String APPLE_JWT_AUD_URL = "https://appleid.apple.com";
    /**
     * 生成clientSecret
     *
     * @param kid
     * @param teamId
     * @param clientId
     * @param primaryKey(寫完發(fā)現(xiàn),命名有誤,privateKey)
     * @return
     */
    public String generateClientSecret(String kid, String teamId,
            String clientId, String primaryKey) {
        Map<String, Object> header = new HashMap<>();
        header.put("kid", kid);
        long second = System.currentTimeMillis() / 1000;

        //將private key字符串轉換成PrivateKey 對象
        PrivateKey privateKey = null;
        try {
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
                    readPrimaryKey(primaryKey));
            KeyFactory keyFactory = KeyFactory.getInstance("EC");
            privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 此處只需PrimaryKey
        Algorithm algorithm = Algorithm.ECDSA256(null,
                (ECPrivateKey) privateKey);
        // 生成JWT格式的client_secret
        String secret = JWT.create().withHeader(header).withClaim("iss", teamId)
                .withClaim("iat", second).withClaim("exp", 86400 * 180 + second)
                .withClaim("aud", APPLE_JWT_AUD_URL).withClaim("sub", clientId)
                .sign(algorithm);
        return secret;
    }

    private byte[] readPrimaryKey(String primaryKey) {
        StringBuilder pkcs8Lines = new StringBuilder();
        BufferedReader rdr = new BufferedReader(new StringReader(primaryKey));
        String line = "";
        try {
            while ((line = rdr.readLine()) != null) {
                pkcs8Lines.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 需要注意刪除 "BEGIN" and "END" 行, 以及空格
        String pkcs8Pem = pkcs8Lines.toString();
        pkcs8Pem = pkcs8Pem.replace("-----BEGIN PRIVATE KEY-----", "");
        pkcs8Pem = pkcs8Pem.replace("-----END PRIVATE KEY-----", "");
        pkcs8Pem = pkcs8Pem.replaceAll("\\s+", "");

        // Base64 轉碼
        return Base64.decodeBase64(pkcs8Pem);
    }

3.驗證并登錄

  • 最后一塊拼圖client_secret獲取到之后,就可以去請求獲取token了。
        public static final String APPLE_AUTH_TOKEN_URL = "https://appleid.apple.com/auth/token";

        // POST 請求
        Map<String, String> header = new HashMap<>();
        header.put("content-type", " application/x-www-form-urlencoded");

        // authorizationCode僅能使用一次
        Map<String, String> form = new HashMap<>();
        form.put("client_id", clientId);
        form.put("client_secret", clientSecret);
        form.put("code", authorizationCode);
        form.put("grant_type", "authorization_code");
        JSONObject result = HttpClientUtil.sendHttpPostByFormMap(
                APPLE_AUTH_TOKEN_URL, form, header);
  • 獲取到結果:


    返回結果
  • 只需要id_token即可,id_token是JWT格式的,可以直接放入jwt.io里面解析,注意到箭頭標記的三段,分別對應JWT的header,payload,verify signature。截取其中的payload。

    jwt.io觀察json key-value

  • base64解碼截取的payload,是一個json,取sub的值就是我們要的apple user。

  • 與前端傳過來的user進行比對,如果一致,就代表驗證成功,然后執(zhí)行登錄/注冊邏輯。

四、總結

  • 重點在于client_secret的generate以及JWT的sign&decode。

五、參考文獻

六、相關資源

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容