-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #87 from Central-MakeUs/dev
[Feature] 애플 로그인 구현
- Loading branch information
Showing
11 changed files
with
361 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
114 changes: 114 additions & 0 deletions
114
src/main/java/com/cmc/mercury/global/oauth/apple/AppleClientSecretService.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
package com.cmc.mercury.global.oauth.apple; | ||
|
||
import com.auth0.jwt.JWT; | ||
import com.auth0.jwt.algorithms.Algorithm; | ||
import com.auth0.jwt.interfaces.DecodedJWT; | ||
import com.cmc.mercury.global.exception.CustomException; | ||
import com.cmc.mercury.global.exception.ErrorCode; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
//import org.apache.commons.io.IOUtils; | ||
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; | ||
import org.bouncycastle.openssl.PEMParser; | ||
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; | ||
import org.springframework.beans.factory.annotation.Value; | ||
//import org.springframework.core.io.ClassPathResource; | ||
import org.springframework.stereotype.Service; | ||
|
||
//import java.io.IOException; | ||
//import java.io.InputStream; | ||
import java.io.IOException; | ||
import java.io.StringReader; | ||
import java.nio.charset.StandardCharsets; | ||
import java.security.PrivateKey; | ||
import java.security.interfaces.ECPrivateKey; | ||
import java.time.LocalDateTime; | ||
import java.time.ZoneId; | ||
import java.util.Base64; | ||
import java.util.Date; | ||
import java.util.HashMap; | ||
import java.util.Map; | ||
|
||
@Service | ||
@RequiredArgsConstructor | ||
@Slf4j | ||
public class AppleClientSecretService { | ||
|
||
// @Value("${apple.key-path}") | ||
// private String keyPath; | ||
@Value("${apple.key-content}") | ||
private String appleKeyContent; | ||
|
||
@Value("${apple.kid}") | ||
private String keyId; | ||
|
||
@Value("${apple.tid}") | ||
private String teamId; | ||
|
||
@Value("${apple.cid}") | ||
private String clientId; | ||
|
||
public String createClientSecret() { | ||
try { | ||
// 직접 파일 업로드 시 사용 | ||
// log.info("Reading private key from path: {}", keyPath); | ||
// PrivateKey privateKey = getPrivateKey(); | ||
|
||
// Base64 디코딩 | ||
byte[] decoded = Base64.getDecoder().decode(appleKeyContent); | ||
// PEM 파싱 → PrivateKey | ||
PrivateKey privateKey = getPrivateKey(new String(decoded, StandardCharsets.UTF_8)); | ||
log.info("Private key successfully created"); | ||
|
||
Map<String, Object> headerClaims = new HashMap<>(); | ||
headerClaims.put("kid", keyId); | ||
headerClaims.put("alg", "ES256"); | ||
|
||
Date expirationDate = Date.from(LocalDateTime.now().plusDays(30) | ||
.atZone(ZoneId.systemDefault()).toInstant()); | ||
// code/token 교환 직전에 항상 client secret 새로 생성 | ||
String clientSecret = JWT.create() | ||
.withHeader(headerClaims) | ||
.withKeyId(keyId) | ||
.withIssuer(teamId) | ||
.withAudience("https://appleid.apple.com") | ||
.withSubject(clientId) | ||
.withExpiresAt(expirationDate) | ||
.withIssuedAt(new Date(System.currentTimeMillis())) | ||
.sign(Algorithm.ECDSA256(null, (ECPrivateKey) privateKey)); | ||
|
||
log.info("Generated client secret: {}", clientSecret); | ||
|
||
// JWT 디코딩해서 내용 확인 | ||
DecodedJWT jwt = JWT.decode(clientSecret); | ||
log.info("Decoded JWT - Header: {}", jwt.getHeader()); | ||
log.info("Decoded JWT - Payload: {}", jwt.getPayload()); | ||
|
||
return clientSecret; | ||
|
||
} catch (Exception e) { | ||
throw new CustomException(ErrorCode.APPLE_CLIENT_SECRET_ERROR); | ||
} | ||
} | ||
|
||
public PrivateKey getPrivateKey(String keyContent) throws IOException { | ||
|
||
try { | ||
// 직접 파일 업로드 시 사용 | ||
// ClassPathResource resource = new ClassPathResource(keyPath); | ||
// InputStream in = resource.getInputStream(); | ||
|
||
// PEMParser pemParser = new PEMParser(new StringReader(IOUtils.toString(in, StandardCharsets.UTF_8))); | ||
PEMParser pemParser = new PEMParser(new StringReader(keyContent)); | ||
PrivateKeyInfo object = (PrivateKeyInfo) pemParser.readObject(); | ||
log.info("PEMParser created"); | ||
log.info("PEM object read, type: {}", object != null ? object.getClass().getName() : "null"); | ||
JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); | ||
|
||
return converter.getPrivateKey(object); | ||
|
||
} catch (IOException e) { | ||
throw new CustomException(ErrorCode.APPLE_PRIVATE_KEY_ERROR); | ||
} | ||
} | ||
} |
74 changes: 74 additions & 0 deletions
74
src/main/java/com/cmc/mercury/global/oauth/apple/AppleIdTokenVerifier.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
package com.cmc.mercury.global.oauth.apple; | ||
|
||
|
||
import com.auth0.jwk.Jwk; | ||
import com.auth0.jwk.JwkProvider; | ||
import com.auth0.jwk.UrlJwkProvider; | ||
import com.auth0.jwt.JWT; | ||
import com.auth0.jwt.JWTVerifier; | ||
import com.auth0.jwt.algorithms.Algorithm; | ||
import com.auth0.jwt.interfaces.DecodedJWT; | ||
import com.cmc.mercury.global.exception.CustomException; | ||
import com.cmc.mercury.global.exception.ErrorCode; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.stereotype.Service; | ||
|
||
import java.net.URL; | ||
import java.security.PublicKey; | ||
import java.security.interfaces.ECPublicKey; | ||
import java.security.interfaces.RSAPublicKey; | ||
|
||
@Service | ||
@Slf4j | ||
public class AppleIdTokenVerifier { | ||
|
||
@Value("${apple.cid}") | ||
private String clientId; | ||
|
||
public DecodedJWT verify(String idToken) { | ||
try { | ||
|
||
// id_token 헤더 파싱 (kid, alg 등 확인) | ||
DecodedJWT unverifiedJWT = JWT.decode(idToken); | ||
String keyId = unverifiedJWT.getKeyId(); | ||
String algFromToken = unverifiedJWT.getAlgorithm(); | ||
log.info("Apple id_token의 kid = {}, alg = {}", keyId, algFromToken); | ||
|
||
// 애플의 공개키 엔드포인트 URL | ||
URL appleJwkUrl = new URL("https://appleid.apple.com/auth/keys"); | ||
JwkProvider jwkProvider = new UrlJwkProvider(appleJwkUrl); | ||
Jwk jwk = jwkProvider.get(keyId); | ||
PublicKey publicKey = jwk.getPublicKey(); | ||
log.info("애플 공개키 성공적으로 가져옴, key type: {}", publicKey.getAlgorithm()); | ||
|
||
// 공개키가 RSA인지 EC인지 구분하여 Algorithm 인스턴스 생성 | ||
Algorithm algorithm; | ||
if ("EC".equalsIgnoreCase(publicKey.getAlgorithm())) { | ||
// EC 키인 경우 | ||
algorithm = Algorithm.ECDSA256((ECPublicKey) publicKey, null); | ||
} else if ("RSA".equalsIgnoreCase(publicKey.getAlgorithm())) { | ||
// RSA 키인 경우 | ||
algorithm = Algorithm.RSA256((RSAPublicKey) publicKey, null); | ||
} else { | ||
throw new IllegalArgumentException("지원하지 않는 공개키 타입: " + publicKey.getAlgorithm()); | ||
} | ||
|
||
// JWTVerifier를 생성하여 서명, issuer, audience 등의 클레임 검증 | ||
JWTVerifier verifier = JWT.require(algorithm) | ||
.withIssuer("https://appleid.apple.com") | ||
.withAudience(clientId) | ||
.build(); | ||
|
||
// 서명 및 필수 클레임 검증 | ||
DecodedJWT verifiedJwt = verifier.verify(idToken); | ||
log.info("id_token 검증 성공: subject={}, issuer={}", verifiedJwt.getSubject(), verifiedJwt.getIssuer()); | ||
|
||
return verifiedJwt; | ||
|
||
} catch (Exception e) { | ||
log.error("id_token 검증 실패", e); | ||
throw new CustomException(ErrorCode.APPLE_TOKEN_VALIDATION_ERROR); | ||
} | ||
} | ||
} |
52 changes: 52 additions & 0 deletions
52
src/main/java/com/cmc/mercury/global/oauth/apple/CustomRequestEntityConverter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package com.cmc.mercury.global.oauth.apple; | ||
|
||
import com.cmc.mercury.global.exception.CustomException; | ||
import com.cmc.mercury.global.exception.ErrorCode; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.core.convert.converter.Converter; | ||
import org.springframework.http.RequestEntity; | ||
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest; | ||
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequestEntityConverter; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.util.MultiValueMap; | ||
|
||
@Component | ||
@RequiredArgsConstructor | ||
@Slf4j | ||
public class CustomRequestEntityConverter implements Converter<OAuth2AuthorizationCodeGrantRequest, RequestEntity<?>> { | ||
|
||
private final AppleClientSecretService appleClientSecretService; | ||
private final OAuth2AuthorizationCodeGrantRequestEntityConverter defaultConverter = | ||
new OAuth2AuthorizationCodeGrantRequestEntityConverter(); | ||
|
||
@Override | ||
public RequestEntity<?> convert(OAuth2AuthorizationCodeGrantRequest request) { | ||
|
||
log.info("Converting OAuth2 request for provider: {}", request.getClientRegistration().getRegistrationId()); | ||
RequestEntity<?> entity = defaultConverter.convert(request); | ||
String registrationId = request.getClientRegistration().getRegistrationId(); | ||
|
||
MultiValueMap<String, String> params = (MultiValueMap<String, String>) entity.getBody(); | ||
|
||
if ("apple".equals(registrationId)) { | ||
try { | ||
// client_secret JWT 생성 및 설정 | ||
String clientSecret = appleClientSecretService.createClientSecret(); | ||
params.set("client_secret", clientSecret); | ||
|
||
} catch (Exception e) { | ||
throw new CustomException(ErrorCode.APPLE_CLIENT_SECRET_ERROR); | ||
} | ||
} | ||
|
||
log.info("Converter의 param: {}", params); | ||
|
||
return new RequestEntity<>( | ||
params, | ||
entity.getHeaders(), | ||
entity.getMethod(), | ||
entity.getUrl() | ||
); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.