老表瞧一瞧,懒人工具类sign with apple 配置好需要的参数APPLICATION_ID 、SECRET_KEY 、FILE_KID 、TEAM_ID ,调getUserInfo()方法就完工了,不废话,看工具类
package com.zjtx.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwk.Jwk;
import com.zjtx.dto.AppleReturnTokenDTO;
import com.zjtx.util.exception.ServiceException;
import io.jsonwebtoken.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.HashMap;
import java.util.Map;
public class AppleThirdUtils {
@Autowired
static RestTemplate restTemplate;
private static final Logger logger = LoggerFactory.getLogger(AppleThirdUtils.class);
private static final String APPLICATION_ID = "";
private static final String SECRET_KEY = "";
private static final String FILE_KID = "";
private static final String TEAM_ID = "";
private static final String GRANT_TYPE = "authorization_code";
private static final String PUBLIC_KEY_URL = "https://appleid.apple.com/auth/keys";
private static final String GET_ID_TOKEN = "https://appleid.apple.com/auth/token";
private static final String APPLE_URL = "https://appleid.apple.com";
private static final String AUTH_TIME = "auth_time";
private static String getValidateCode(String code){
restTemplate = new RestTemplate();
//请求苹果验证接口
ResponseEntity<String> response = restTemplate.postForEntity(GET_ID_TOKEN, AppleThirdUtils.getRequestParams(code), String.class);
return response.getBody();
}
private static HttpEntity<MultiValueMap<String, String>> getRequestParams(String code){
//构建请求参数
HttpHeaders headers = new HttpHeaders();
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
map.add("client_id", APPLICATION_ID);
map.add("client_secret", getSecretKey());
map.add("code", code);
map.add("grant_type", GRANT_TYPE);
return new HttpEntity<>(map, headers);
}
private static byte[] readKey() {
return Base64.decodeBase64(SECRET_KEY);
}
private static String getSecretKey(){
try {
Map<String, Object> header = new HashMap<>(16);
// 参考后台配置kid
header.put("kid", FILE_KID);
Map<String, Object> claims = new HashMap<>(16);
// 参考后台配置 team id
claims.put("iss", TEAM_ID);
long now = System.currentTimeMillis() / 1000;
claims.put("iat", now);
// 最长半年,单位秒
claims.put("exp", now + 86400 * 30);
// 苹果官网网址
claims.put("aud", APPLE_URL);
// client_id (应用id)
claims.put("sub", APPLICATION_ID);
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(readKey());
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
return Jwts.builder().setHeader(header).setClaims(claims).signWith(SignatureAlgorithm.ES256, privateKey).compact();
}catch (Exception e){
logger.error("获取apple密钥失败:",e);
throw new ServiceException("获取apple密钥失败:",e);
}
}
private static String verify(String identityToken) {
try {
if (identityToken.split("\\.").length <= 1) {
return null;
}
String firstDate = new String(Base64.decodeBase64(identityToken.split("\\.")[0]), "UTF-8");
String claim = new String(Base64.decodeBase64(identityToken.split("\\.")[1]));
String kid = JSONObject.parseObject(firstDate).get("kid").toString();
String aud = JSONObject.parseObject(claim).get("aud").toString();
String sub = JSONObject.parseObject(claim).get("sub").toString();
String response = verify(getPublicKey(kid), identityToken, aud, sub);
return "SUCCESS".equals(response) ? claim : null;
} catch (Exception e) {
logger.error("解密TOKEN失败", e);
throw new ServiceException("解密TOKEN失败", e);
}
}
private static String verify(PublicKey key, String jwt, String audience, String subject) throws Exception {
String result = "FAIL";
JwtParser jwtParser = Jwts.parser().setSigningKey(key);
jwtParser.requireIssuer(APPLE_URL);
jwtParser.requireAudience(audience);
jwtParser.requireSubject(subject);
try {
Jws<Claims> claim = jwtParser.parseClaimsJws(jwt);
if (claim != null && claim.getBody().containsKey(AUTH_TIME)) {
result = "SUCCESS";
return result;
}
} catch (ExpiredJwtException e) {
logger.error("苹果token过期", e);
throw new Exception("苹果token过期", e);
} catch (SignatureException e) {
logger.error("苹果token非法", e);
throw new Exception("苹果token非法", e);
}
return result;
}
private static PublicKey getPublicKey(String kid) {
try {
restTemplate = new RestTemplate();
//请求苹果验证接口
String response = restTemplate.getForObject(PUBLIC_KEY_URL, String.class);
if (StringUtils.isBlank(response)){
return null;
}
JSONObject data = JSONObject.parseObject(response);
JSONArray jsonArray = data.getJSONArray("keys");
if (jsonArray.isEmpty()) {
return null;
}
//通过kid,n和e的值获取苹果公钥字符串
for (Object object : jsonArray) {
JSONObject json = ((JSONObject) object);
//公钥有多个,只取第一个会报SignatureException异常,得根据token的kid取
if (json.getString("kid").equals(kid)) {
String n = json.getString("n");
String e = json.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);
}
}
} catch (Exception e) {
logger.error("getPublicKey异常! {}", e.getMessage());
e.printStackTrace();
}
return null;
}
public static String getUserInfo(String code){
//获取用户信息
JSONObject jsonObject = JSONObject.parseObject(getValidateCode(code));
AppleReturnTokenDTO appleReturnTokenDTO = JSONObject.toJavaObject(jsonObject, AppleReturnTokenDTO.class);
String idToken = appleReturnTokenDTO.getId_token();
return AppleThirdUtils.verify(idToken);
}
}
老表,光这么搞是不行滴,实体类也粘下:
package com.zjtx.dto;
public class AppleReturnTokenDTO {
private String access_token;
private String token_type;
private Integer expires_in;
private String refresh_token;
private String id_token;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
public Integer getExpires_in() {
return expires_in;
}
public void setExpires_in(Integer expires_in) {
this.expires_in = expires_in;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public String getId_token() {
return id_token;
}
public void setId_token(String id_token) {
this.id_token = id_token;
}
}
最后就是maven依赖喽
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>jwks-rsa</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore-nio -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore-nio</artifactId>
<version>4.4.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore-nio -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore-nio</artifactId>
<version>4.4.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpasyncclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1.4</version>
</dependency>
说明:说明我懒,再有不懂的加微信哦:wangdeyu66666(码农汪)
注意点:io.jsonwebtoken.SignatureException: JWT signature does not * match locally computed signature. JWT validity cannot be asserted and should
这个异常是因为获取的公钥是一个数组,里面有多个,只取第一个的话会报这个异常,得根据identityToken里的kid去匹配到底取哪一个,要不然就会报签名不一致的问题,当然,我的工具类里已经处理了这个问题