Java 接入苹果登录

2024-07-20后端5 分钟703 次阅读
AI 摘要鱼粮不足,AI 今天先歇着 · 正文在下面

前言

为什么要用苹果登录?在国内大多数人应该都是使用的微信登录或者手机号一键登录多一些。之所以要开发苹果登录,可能大多是因为苹果的霸王条款:要求只要在苹果商店上架的应用,凡是接入了其他第三方登录,必须接入苹果登录。

苹果登录涉及非对称加密、JWT、第三方登录,下边我会简单介绍下:

  • 非对称加密:我们知道对称加密在加解密时使用的秘钥内容是相同的,而非对称加密在加密和解密时使用不同的秘钥。我们把这两个不同的秘钥一个称为私钥,一个称为公钥。一般私钥由我们自己保留不对外公开,而公钥则可以对外公开下载。这样有什么好处呢?举个例子:我们发布一则公告,使用私钥进行加密,然后把公告放到互联网上。想要看公告的人直接下载我们的公钥,然后用公钥解密公告即可。这样别人就无法仿造我们的公告,因为只有我们提供的公钥才能解密,从而达到对公告信任的目的。
  • JWT:我们先看看苹果的JWT:
    json 复制代码
    {"kid": "W6WcOKB","alg": "RS256"}.{"iss":"https://appleid.apple.com","aud":"com.test","exp":1687776521,"iat":1687690121,"sub":"001001.0bb42737edf44688850c5de5e666d9e.1024","c_hash":"FXhhsDY1Dpabo8_GTID-Lw","auth_time":1687690121,"nonce_supported":true,"real_user_status":2}.xxxxxxxxxxxxxxxxxxxxxxxxxx
    • 第一段:{"kid": "W6WcOKB","alg": "RS256"} 我们称为头部,标记了这个JWT通过RS256进行加密,(这里的kid是对应的公钥id,这个是苹果特有的)。
    • 第二段:{"iss":"https://appleid.apple.com","aud":"com.test","exp":1687776521,"iat":1687690121,"sub":"001001.0bb42737edf44688850c5de5e666d9e.1024","c_hash":"FXhhsDY1Dpabo8_GTID-Lw","auth_time":1687690121,"nonce_supported":true,"real_user_status":2}。这里我们只说关键的几个参数:iss:发布人,固定是苹果的域名;aud:应用的包名;sub:当前用户的唯一ID,类似微信等第三方登录的OpenID;
    • 第三段:就是校验和类似的东西,没有详细的研究苹果是怎么实现的,但是我们理解技术不必太过纠结,知道他是个校验和的东西就行。比如我可以这么实现,首先将前面的两个部分拼接成一个字符串,然后求一个摘要,再用私钥进行加密后作为第三部分。需要校验时,先求前两部分摘要,然后用公钥解密第三方部分,看解密的结果和我们求出的摘要是否相等即可。
  • 第三方登录:其实问为什么需要第三方登录更好。随着我们使用的应用越来越多,如果我们每个都创建一个账户和密码,简直就是噩梦。而我们有微信账号,如果可以直接用微信账号登录多好,一个账号走天下,只要记住微信的密码,能登录微信就可以了,再也不怕忘记密码了。至于通常如何实现第三方登录,可以去了解下OAuth2,这里就不再多说了,不是本文的重点。

苹果登录原理

  1. 首先,当你在应用内点击苹果登陆按钮时,苹果会生成一系列的参数给你,其中最重要的一个参数是:identityToken。这个参数的值就是一个JWT。这个JWT是通过苹果的私钥加密的。
  2. 我们将这个identityToken传给我们的后台服务,后台服务从苹果提供的公钥下载地址下载公钥,然后使用公钥验证这个JWT是否合法。
  3. 在合法的前提下,我们看一下iss是否是苹果(显然是),再看aud是不是你自己的包名(别人的应用也可以生成一个token,也可以通过校验,但是包名肯定和你的不同)。都校验通过了,说明这是一个合法JWT。然后我们就取sub作为苹果的OpenId,记录到我们后台的用户表里即可(如果没有用户则创建,如果有则绑定)。等到再次登录的时候,则用sub查询有没有对应的用户,如果有,则直接让其登录即可。

代码实现

我的项目是 SpringBoot + gradle,下面是核心依赖:

gradle 复制代码
implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5'

api 'com.alibaba:fastjson:1.2.67_noneautotype2'

api 'org.apache.httpcomponents:httpcore:4.4.12'
api('org.apache.httpcomponents:httpclient:4.5.13') {
    exclude(module: 'commons-logging')
}

编写 IAppleService

java 复制代码
package com.salmon.service;

/**
 * Apple相关API
 *
 * @author Salmon
 * @since 2024-07-20
 */
public interface IAppleService {

    /**
     * 登录
     *
     * @param identityToken JWT身份令牌
     */
    String login(String identityToken) throws Exception;
}

编写 AppleServiceImpl

java 复制代码
package com.salmon.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.salmon.service.IAppleService;
import com.salmon.util.HttpClientUtil;
import io.jsonwebtoken.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;
import java.util.Objects;

/**
 * Apple相关API实现
 *
 * @author Salmon
 * @since 2024-07-20
 */
@Service
@Slf4j
@AllArgsConstructor
public class AppleServiceImpl implements IAppleService {

    private HttpClientUtil httpClientUtil;

    /**
     * 登录
     *
     * @param identityToken JWT身份令牌
     */
    @Override
    public String login(String identityToken) throws Exception {
        // 从identityToken中获取头部和载荷
        String firstDate;
        String claim;
        firstDate = new String(Base64.decodeBase64(identityToken.split("\\.")[0]), StandardCharsets.UTF_8);
        claim = new String(Base64.decodeBase64(identityToken.split("\\.")[1]), StandardCharsets.UTF_8);

        // 开发者帐户中获取的 10 个字符的标识符密钥
        String kid = JSONObject.parseObject(firstDate).get("kid").toString();
        String aud = JSONObject.parseObject(claim).get("aud").toString();
        String sub = JSONObject.parseObject(claim).get("sub").toString();

        // 获取公钥
        PublicKey publicKey = this.getPublicKey(kid);
        if (Objects.isNull(publicKey)) {
            throw new RuntimeException("apple授权登录的数据异常");
        }

        // 验证Apple登录的JWT令牌
        boolean result = this.verifyAppleLoginCode(publicKey, identityToken, aud, sub);

        // 返回用户标识符
        if (result) {
            return sub;
        }
        return null;
    }

    /**
     * 验证Apple登录的JWT令牌
     *
     * @param publicKey     公钥
     * @param identityToken JWT身份令牌
     * @param aud           受众
     * @param sub           用户标识符
     * @return 验证结果
     */
    private boolean verifyAppleLoginCode(PublicKey publicKey, String identityToken, String aud, String sub) {
        boolean result = false;
        String appleIssUrl = "https://appleid.apple.com";
        JwtParser jwtParser = Jwts.parserBuilder()
                .setSigningKey(publicKey)
                .requireIssuer(aud)
                .requireSubject(sub)
                .requireIssuer(appleIssUrl).build();
        try {
            Jws<Claims> claim = jwtParser.parseClaimsJws(identityToken);
            if (claim != null && claim.getBody().containsKey("auth_time")) {
                result = true;
            }
        } catch (ExpiredJwtException e) {
            log.error("error identity expire time out", e);
            throw new RuntimeException("apple登录授权identityToken过期", e);
        } catch (SecurityException e) {
            log.error("error identity illegal", e);
            throw new RuntimeException("apple登录授权identityToken非法", e);
        }
        return result;
    }

    /**
     * 获取公钥
     *
     * @param kid 标识符密钥
     * @return 公钥
     */
    private PublicKey getPublicKey(String kid) throws Exception {
        String appleAuthUrl = "https://appleid.apple.com/auth/keys";
        String result = httpClientUtil.get(appleAuthUrl);
        JSONObject content = JSONObject.parseObject(result);
        String keys = content.getString("keys");
        JSONArray keysArray = JSONObject.parseArray(keys);
        if (keysArray.isEmpty()) {
            return null;
        }
        for (Object key : keysArray) {
            JSONObject keyJsonObject = (JSONObject) key;
            if (kid.equals(keyJsonObject.getString("kid"))) {
                String n = keyJsonObject.getString("n");
                String e = keyJsonObject.getString("e");
                BigInteger modulus = new BigInteger(1, Base64.decodeBase64(n));
                BigInteger publicExponent = new BigInteger(1, Base64.decodeBase64(e));
                RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, publicExponent);
                KeyFactory kf = KeyFactory.getInstance("RSA");
                return kf.generatePublic(spec);
            }
        }
        return null;
    }
}

编写 UserController

java 复制代码
package com.salmon.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.salmon.entity.User;
import com.salmon.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 用户前端控制器
 *
 * @author Salmon
 * @since 2024-07-20
 */
@RestController
@Slf4j
@RequestMapping("/user")
@Api(tags = "用户")
@AllArgsConstructor
public class UserController {

    private IAppleService appleService;
    private IUserService userService;
    private HttpServletRequest request;

    /**
     * 苹果登录
     *
     * @param code JWT
     */
    @PostMapping("/appleLogin")
    public String appleLogin(String code) throws Exception {
        String subjectId = appleService.login(code);
        User user = userService.getOne(new QueryWrapper<User>().eq("apple_id", subjectId));
        if (Objects.isNull(user)) {
            user = new User(subjectId, Utils.getIp(request));
            userService.save(user);

        }
        return user;
    }
}
觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句