sign with apple 后端验证一步搞定

宿迁·汪德宇 2020-09-14 04:11:38
想那么多干嘛,用这个工具类改完配置参数,直接调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;

/**
* 苹果登录工具类
* @author WangDeyu (汪德宇)
* @date 2020-09-08 16:10:22
* */
public class AppleThirdUtils {

@Autowired
static RestTemplate restTemplate;

private static final Logger logger = LoggerFactory.getLogger(AppleThirdUtils.class);

/**
* client_id (应用id,从苹果注册应用获取)
* */
private static final String APPLICATION_ID = "";

/**
* 密钥key(从txt文件中获取)
* */
private static final String SECRET_KEY = "";

/**
* p8文件中获取的kid
* */
private static final String FILE_KID = "";

/**
* p8文件中获取的team_id
* */
private static final String TEAM_ID = "";

/**
* 固定值(用于验证token接口)
* */
private static final String GRANT_TYPE = "authorization_code";

/**
* 获取公钥地址
* */
private static final String PUBLIC_KEY_URL = "https://appleid.apple.com/auth/keys";

/**
* 获取验证token地址
* */
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";



/**
* 获取验证的code
* */
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();
}

/**
* 构建验证登录参数
* @author WangDeyu
* */
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);
}

/**
* 读取文件中的密钥key,解密
* */
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);
}
}


/**
* 解密个人信息
*
* @param identityToken APP获取的identityToken
* @return 解密参数:失败返回null
*/
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);
}
}

/**
* 验证token
* */
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;
}


/**
* 获取苹果公钥
*
* @param kid (公钥的id)
* @return PublicKey
*/
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;

/**
* 苹果登录返回的参数
* @author WangDeyu
* */
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>
...全文
133 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

5,657

社区成员

发帖
与我相关
我的任务
社区描述
Web开发应用服务器相关讨论专区
社区管理员
  • 应用服务器社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧