1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
| @Slf4j @Service public class ThirdPartyAuthService {
@Value("${thirdparty.login.google.android.client-id:xxx}") private String googleAndroidClientId;
@Value("${thirdparty.login.google.ios.client-id:xxx}") private String googleIosClientId;
@Value("${thirdparty.login.apple.ios.client-id:xxx}") private String appleIosClientId;
private String googleWebClientId = "xxx";
private static final String APPLE_ISSUER = "https://appleid.apple.com";
private static final String APPLE_KEYS_URL = "https://appleid.apple.com/auth/keys";
private final Cache<String, List<JWK>> jwkCache = Caffeine.newBuilder() .expireAfterWrite(Duration.ofHours(6)) .maximumSize(5) .build();
private static final String APPLE_KEYS_CACHE_KEY = "apple_keys_cache";
GoogleIdTokenVerifier googleIdTokenVerifier = null;
@PostConstruct public void init() { googleIdTokenVerifier = new GoogleIdTokenVerifier.Builder( new NetHttpTransport(), new GsonFactory()) .setAudience(Lists.newArrayList(googleAndroidClientId, googleIosClientId, googleWebClientId)) .build(); }
public ThirdpartyUserProfile getUserProfile(ThirdpartyLoginRequest loginRequest) {
if (loginRequest == null || StringUtils.isAnyBlank(loginRequest.getSource(), loginRequest.getIdToken())) { log.warn("getUserProfile invalid parameter: {}", JSON.toJSONString(loginRequest)); return null; } ThirdpartyTypeEnum thirdpartyTypeEnum = ThirdpartyTypeEnum.of(loginRequest.getSource()); if (thirdpartyTypeEnum == null) { log.warn("getUserProfile invalid source: {}", JSON.toJSONString(loginRequest)); return null; } switch (thirdpartyTypeEnum) { case google: return getGoogleUserProfile(loginRequest); case apple: return getAppleUserProfile(loginRequest); default: break; } return null; }
public ThirdpartyUserProfile getGoogleUserProfile(ThirdpartyLoginRequest loginRequest) { String idTokenString = loginRequest.getIdToken(); try { if (googleIdTokenVerifier == null) { init(); } GoogleIdToken idToken = googleIdTokenVerifier.verify(idTokenString); if (idToken == null) { log.warn("getGoogleUserProfile invalid idToken: {}", JSON.toJSONString(idTokenString)); throw new MyThrowException(ExceptionEnum.INVALID_AUTH_TOKEN); } GoogleIdToken.Payload payload = idToken.getPayload(); String subject = payload.getSubject(); String email = payload.getEmail(); Boolean emailVerified = payload.getEmailVerified(); String name = (String) payload.get("name"); String picture = (String) payload.get("picture");
ThirdpartyUserProfile profile = new ThirdpartyUserProfile(); profile.setEmail(email); profile.setEmailVerified(emailVerified); profile.setSub(subject); profile.setName(name); profile.setPicture(picture); profile.setLocale((String) payload.get("locale")); profile.setGivenName((String) payload.get("given_name")); profile.setFamilyName((String) payload.get("family_name")); profile.setType(ThirdpartyTypeEnum.google.name()); return profile; } catch (Exception e) { log.error("getGoogleUserProfile verify idToken: {}, error:", JSON.toJSONString(idTokenString), e); } return null; }
public ThirdpartyUserProfile getAppleUserProfile(ThirdpartyLoginRequest loginRequest) {
String idTokenString = loginRequest.getIdToken();
try { SignedJWT signedJWT = SignedJWT.parse(idTokenString); String kid = signedJWT.getHeader().getKeyID(); JWSVerifier verifier = getAppleVerifier(kid, true);
if (!signedJWT.verify(verifier)) { verifier = getAppleVerifier(kid, false); if (!signedJWT.verify(verifier)) { log.warn("invalid identityToken: {}", idTokenString); throw new MyThrowException(ExceptionEnum.INVALID_AUTH_TOKEN); } }
JWTClaimsSet claims = signedJWT.getJWTClaimsSet(); if (!APPLE_ISSUER.equals(claims.getIssuer())) { log.warn("invalid identityToken: {}, wrong issuer:{}", idTokenString, claims.getIssuer()); throw new MyThrowException(ExceptionEnum.INVALID_AUTH_TOKEN); } if (!claims.getAudience().contains(appleIosClientId)) { log.warn("invalid identityToken: {}, wrong audiences:{}", idTokenString, JSON.toJSONString(claims.getAudience())); throw new MyThrowException(ExceptionEnum.INVALID_AUTH_TOKEN); } if (claims.getExpirationTime() != null && new Date().after(claims.getExpirationTime())) { log.warn("invalid identityToken: {}, expiration time:{}", idTokenString, claims.getExpirationTime().getTime()); throw new MyThrowException(ExceptionEnum.INVALID_AUTH_TOKEN); }
Map<String, Object> claimsMap = claims.getClaims();
String subject = claims.getSubject(); String email = (String) claimsMap.get("email"); Object emailVerifiedObj = claimsMap.get("email_verified"); Boolean emailVerified = null; if (emailVerifiedObj != null) { emailVerified = Boolean.valueOf(String.valueOf(emailVerifiedObj)); } Boolean isPrimaryEmail = null; Object isPrimaryObj = claimsMap.get("is_private_email"); if (isPrimaryObj != null) { isPrimaryEmail = Boolean.valueOf(String.valueOf(isPrimaryObj)); }
ThirdpartyUserProfile profile = new ThirdpartyUserProfile(); profile.setEmail(email); profile.setEmailVerified(emailVerified); profile.setPrivateEmail(isPrimaryEmail); profile.setSub(subject); profile.setType(ThirdpartyTypeEnum.apple.name()); return profile;
} catch (Exception e) { log.error("getAppleUserProfile verify idToken: {}, error:", JSON.toJSONString(idTokenString), e); } return null; }
private JWSVerifier getAppleVerifier(String kid, boolean useCache) { try { List<JWK> jwks = useCache ? getApplePublicJwksFromCache() : getApplePublicJwks(); JWK applePublicJwk = jwks.stream() .filter(k -> k.getKeyID().equals(kid)) .findFirst() .orElse(null); if (applePublicJwk == null) { log.warn("get jwk failed, kid: {}", kid); throw new MyThrowException(ExceptionEnum.SERVICE_INTERVAL); } RSAPublicKey publicKey = ((RSAKey) applePublicJwk).toRSAPublicKey(); JWSVerifier verifier = new RSASSAVerifier(publicKey); return verifier; } catch (Exception e) { log.error("getAppleVerifier error: ", e); } throw new MyThrowException(ExceptionEnum.SERVICE_INTERVAL); }
private List<JWK> getApplePublicJwks() {
try { JWKSet jwkSet = JWKSet.load(new URL(APPLE_KEYS_URL)); List<JWK> jwks = jwkSet.getKeys(); if (!CollectionUtils.isEmpty(jwks)) { jwkCache.put(APPLE_KEYS_CACHE_KEY, jwks); } return jwks; } catch (Exception e) { log.error("getApplePublicJwks error: ", e); } return Collections.emptyList(); }
private List<JWK> getApplePublicJwksFromCache() { try { List<JWK> jwks = jwkCache.getIfPresent(APPLE_KEYS_CACHE_KEY); if (CollectionUtils.isEmpty(jwks)) { jwks = getApplePublicJwks(); } return jwks; } catch (Exception e) { log.error("getApplePublicJwks error: ", e); } return Collections.emptyList(); } }
|