Java Apple_Sign in with Apple java

importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONArray;importcom.alibaba.fastjson.JSONObject;importcom.auth0.jwk.Jwk;import io.jsonwebtoken.*;importorg.apache.commons.codec.binary.Base64;importorg.springframework.web.client.RestTemplate;importjava.security.PublicKey;public classAppleUtil {/*** 获取苹果的公钥

*@return*@throwsException*/

private static JSONArray getAuthKeys() throwsException {

String url= "https://appleid.apple.com/auth/keys";

RestTemplate restTemplate= newRestTemplate();

JSONObject json= restTemplate.getForObject(url,JSONObject.class);

JSONArray arr= json.getJSONArray("keys");returnarr;

}public static Boolean verify(String jwt) throwsException{

JSONArray arr=getAuthKeys();if(arr == null){return false;

}

JSONObject authKey= null;//先取苹果第一个key进行校验

authKey = JSONObject.parseObject(arr.getString(0));if(verifyExc(jwt, authKey)){return true;

}else{//再取第二个key校验

authKey = JSONObject.parseObject(arr.getString(1));returnverifyExc(jwt, authKey);

}

}/*** 对前端传来的identityToken进行验证

*@paramjwt 对应前端传来的 identityToken

*@paramauthKey 苹果的公钥 authKey

*@return*@throwsException*/

public static Boolean verifyExc(String jwt, JSONObject authKey) throwsException {

Jwk jwa=Jwk.fromValues(authKey);

PublicKey publicKey=jwa.getPublicKey();

String aud= "";

String sub= "";if (jwt.split("\\.").length > 1) {

String claim= new String(Base64.decodeBase64(jwt.split("\\.")[1]));

aud= JSONObject.parseObject(claim).get("aud").toString();

sub= JSONObject.parseObject(claim).get("sub").toString();

}

JwtParser jwtParser=Jwts.parser().setSigningKey(publicKey);

jwtParser.requireIssuer("https://appleid.apple.com");

jwtParser.requireAudience(aud);

jwtParser.requireSubject(sub);try{

Jws claim =jwtParser.parseClaimsJws(jwt);if (claim != null && claim.getBody().containsKey("auth_time")) {

System.out.println(claim);return true;

}return false;

}catch(ExpiredJwtException e) {return false;

}catch(Exception e) {return false;

}

}/*** 对前端传来的JWT字符串identityToken的第二部分进行解码

* 主要获取其中的aud和sub,aud大概对应ios前端的包名,sub大概对应当前用户的授权的openID

*@paramidentityToken

*@return{"aud":"com.xkj.****","sub":"000***.8da764d3f9e34d2183e8da08a1057***.0***","c_hash":"UsKAuEoI-****","email_verified":"true","auth_time":1574673481,"iss":"https://appleid.apple.com","exp":1574674081,"iat":1574673481,"email":"****@qq.com"}*/

public staticJSONObject parserIdentityToken(String identityToken){

String[] arr= identityToken.split("\\.");

Base64 base64= newBase64();

String decode= new String (base64.decodeBase64(arr[1]));

String substring= decode.substring(0, decode.indexOf("}")+1);

JSONObject jsonObject=JSON.parseObject(substring);returnjsonObject;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值