JWT方式(Google,Apple)
获取公钥
https://appleid.apple.com/auth/keys
https://www.googleapis.com/oauth2/v3/certs
公钥校验
public static Boolean verifyAppleLoginToken(String token,String subject) throws IOException {
//先从token中解析出HEADER部分的kid,然后从苹果提供的公钥获取url中获取生成rsa公钥所需的n和e
DecodedJWT decodedJWT = JWT.decode(token);
System.out.println(JSON.toJSONString(decodedJWT));
List<Item> keyList = APPLE_KEYS.toJavaList(Item.class);
String n = null, e = null;
for (Item item : keyList) {
if (item.getKid().equals(kid)) {
n = item.getN();
e = item.getE();
}
}
//各个版本的base64解码实现不太一样,目前发现只有apache的base64可以解析成功
BigInteger bigIntModulus = new BigInteger(1, org.apache.commons.codec.binary.Base64.decodeBase64(n));
BigInteger bigIntPrivateExponent = new BigInteger(1, org.apache.commons.codec.binary.Base64.decodeBase64(e));
try {
//使用生成的RSA公钥验证token的SIGNATURE部分是否合法,(同时验证ISSUER,SUBJECT,AUDIENCE是否合法)
RSAPublicKeyImpl rsaPublicKey = new RSAPublicKeyImpl(bigIntModulus, bigIntPrivateExponent);
Algorithm algorithm = Algorithm.RSA256(rsaPublicKey, null);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer(ISSUER)
.withSubject(subject)
.withAudience(AUDIENCE)
.build();
DecodedJWT jwt = verifier.verify(token);
System.out.println(JSON.toJSONString(jwt));
} catch (JWTVerificationException ex1) {
System.out.println(ex1.getMessage());
return false;
} catch (InvalidKeyException ex2) {
System.out.println(ex2.getMessage());
return false;
}
return true;
}
接口请求(Facebook)
https://graph.facebook.com/debug_token?access_token=&input_token=
OAUTH形式接口请求(Twitter)
https://api.twitter.com/1.1/account/verify_credentials.json