不得提一嘴,苹果的开发者文档写的真不怎么样,可能是我英语水平比较菜吧。。。
这里只介绍基于JWT的算法的验证方式,据说基于授权码的后端验证比较麻烦,csdn上有位老哥也许是老弟搞了几天都没成功!话说回来基于JWT的算法的验证的我也搞了好久,还是在iOS小哥哥的帮助下搞定的!
苹果返回的token,前两段解析出来的数据很有用,第一段用到的是kid,第二段就是具体的用户数据了,data1是第一段解出来的数据,data2是第二解出来的数据
{
“data1”:{
“kid”:”123″,//用此字段生成publicKey
“alg”:”RS256″
},
“data2”:{
“aud”:”com.kuochan.ios”,
“sub”:”一串字符串苹果的uid”,
“c_hash”:””,
“nonce_supported”:true,
“email_verified”:”true”,
“auth_time”:1591845237,
“iss”:”https://appleid.apple.com”,
“exp”:1591845837,
“iat”:1591845237,
“email”:”admin@kuochan.com”
}
}
遇到的错误:
JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.
这个错误产生的原因为是因为没有通过kid去生成PublicKey,因为通过苹果获取的key有多个,我要先把identityToken里面的kid解析出来,然后拿着kid再去生成key
废话不多说直接上代码
maven 依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
Java代码:
package com.guessyoulike.open.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guessyoulike.open.utils.HttpProxyUtil;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
* 登录授权登录
*
* @author guessyoulike.com
* @date 2020/6/3 6:58 PM
*/
@Slf4j
@RestController
@RequestMapping(value = "/apple")
public class AppleController {
private static final Logger LOGGER = LoggerFactory.getLogger(AppleController.class);
/**
* 苹果登录apple sign in
*
* @param identityToken
* @return
*/
@RequestMapping(value = "/login/verify", method = RequestMethod.POST)
public Map loginVerify(@RequestParam("identityToken") String identityToken) {
try {
Map<String, Object> appleUser = getAppleUserInfo(identityToken);
if (appleUser == null) {
return null;
}
LOGGER.info("AppleController.loginVerify user info : {}", appleUser);
return appleUser;
} catch (Exception e) {
LOGGER.error("AppleController.loginVerify error:{}", e);
return null;
}
}
/**
* 解密苹果用户信息
*
* @param identityToken
* @return
*/
private Map<String, Object> getAppleUserInfo(String identityToken) {
try {
String[] identityTokens = identityToken.split("\\.");
Map<String, Object> data1 = JSONObject.parseObject(new String(Base64.decodeBase64(identityTokens[0]), "UTF-8"));
Map<String, Object> data2 = JSONObject.parseObject(new String(Base64.decodeBase64(identityTokens[1]), "UTF-8"));
String kid = (String) data1.get("kid");
String aud = (String) data2.get("aud");
String sub = (String) data2.get("sub");
if (verify(identityToken, kid, aud, sub)) {
Map<String, Object> data = new HashMap<>(2);
data.put("data1", data1);
data.put("data2", data2);
return data;
}
} catch (Exception e) {
LOGGER.error("AppleController.getAppleUserInfo error:{}", e);
}
return null;
}
/**
* 验证token
*
* @param identityToken
* @param aud
* @param sub
* @return
*/
private boolean verify(String identityToken, String kid, String aud, String sub) {
PublicKey publicKey = getPublicKey(kid);
JwtParser jwtParser = Jwts.parser().setSigningKey(publicKey);
jwtParser.requireIssuer("https://appleid.apple.com");
jwtParser.requireAudience(aud);
jwtParser.requireSubject(sub);
try {
Jws<Claims> claim = jwtParser.parseClaimsJws(identityToken);
String authKey = "auth_time";
return claim != null && claim.getBody().containsKey(authKey);
} catch (ExpiredJwtException e) {
LOGGER.error("AppleController.verify identityToken expired:{}", e);
} catch (Exception e) {
LOGGER.error("AppleController.verify error:{}", e);
}
return false;
}
/**
* 根据kid生成公钥
*
* @param kid
* @return 构造好的公钥
*/
private PublicKey getPublicKey(String kid) {
try {
String str = HttpProxyUtil.doGet("https://appleid.apple.com/auth/keys");
JSONObject data = JSONObject.parseObject(str);
JSONArray keysJsonArray = data.getJSONArray("keys");
String n = "";
String e = "";
for (int i = 0; i < keysJsonArray.size(); i++) {
JSONObject jsonObject = keysJsonArray.getJSONObject(i);
if (StringUtils.equals(jsonObject.getString("kid"), kid)) {
n = jsonObject.getString("n");
e = jsonObject.getString("e");
}
}
final BigInteger modulus = new BigInteger(1, Base64.decodeBase64(n));
final BigInteger publicExponent = new BigInteger(1, Base64.decodeBase64(e));
final RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, publicExponent);
final KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
} catch (final Exception e) {
LOGGER.error("AppleController.getPublicKey error:{}", e);
}
return null;
}
}
完整代码Git地址:https://gitee.com/spring-projects/java-common-module
转载请注明:扩产网 » 苹果授权登录 apple sign in Java服务端