/**
* AUD 플랫폼의 AP Token 발급 호출용 샘플 JAVA
*/
public class AudGetApToken {
private static final String AUD_AP_TOKEN_URL = "aud7 플랫폼주소/matrix/api/auth/sign/ap/token";
/**
* audApId , audApPw 는 AUD 플랫폼에 등록한 Application 공통 계정을 사용
* 파라메터로 전달 시에 암호화에 대한 처리하여 Application용 id / pw가 유출되지 않도록 구성
*/
public static String getAPToken(String audApId , String audApSecretKey , String userCode) {
HttpURLConnection connection = null;
try{
if ((audApId == null || audApId.isEmpty()) || (audSecretKey == null || audSecretKey.isEmpty())){
System.out.println("AUD 플랫폼에서 application 인증을 위한 id,pw에 대한 정보가 없습니다.");
return null ;
}
// aud7 플랫폼에서 발급받은 secret key를 ssh의 private key로 서명하여 전달한다.
PrivateKey privateKey = loadPrivateKey("D:\\tomcat\\apache-tomcat-7.0.107-windows-x64\\apache-tomcat-7.0.107\\webapps\\examples\\aud\\apSSH\\aud_id_rsa");
// aud7 secret key 서명 생성
String signedMessage = signMessage(audSecretKey, privateKey);
// header 설정은 아래처럼 해주세요.
Map<String, String> requestHeaders = new HashMap();
requestHeaders.put("X-AUD-AP-Id", audApId);
requestHeaders.put("X-AUD-AP-Secret", signedMessage);
requestHeaders.put("X-AP-UPDATE-ADDR" , AUD_AP_TOKEN_UPDATE_URL);
if (userCode != null || !userCode.isEmpty())
requestHeaders.put("X-AUD-USER" , userCode);
try{
// URL 객체 생성
URL url = new URL(AUD_AP_TOKEN_URL);
connection = (HttpURLConnection) url.openConnection();
}catch(MalformedURLException e){
System.out.println("AUD 플랫폼 주소가 잘못되었습니다.");
return null;
}catch(IOException e){
System.out.println("연결이 실패했습니다 [api url:"+ AUD_AP_TOKEN_URL +"]");
return null ;
}
// HTTP 메서드 설정
connection.setRequestMethod("POST");
for(Map.Entry<String, String> header :requestHeaders.entrySet()) {
connection.setRequestProperty(header.getKey(), header.getValue());
}
// 응답 코드 확인
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK){
String apAccessToken = connection.getHeaderField("bimatrix_ap_accessToken");
if (apAccessToken == null){
System.out.println("ap token이 정상적으로 발급되지 않았습니다");
return null;
}
else{
return apAccessToken;
}
}else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED){
System.out.println("만료된 ap token 입니다.");
return null;
}
}catch(Exception e){
e.printStackTrace();
}finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
// 개인 키 로딩
private static PrivateKey loadPrivateKey(String path) throws Exception {
// 개인 키 로딩 로직을 구현 (파일 파싱 또는 다른 방법으로)
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Files.readAllBytes(Paths.get(path)));
return keyFactory.generatePrivate(keySpec);
}
// 메시지 서명
private static String signMessage(String message, PrivateKey privateKey) throws Exception {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(message.getBytes());
byte[] signedBytes = signature.sign();
return Base64.getEncoder().encodeToString(signedBytes);
}
}
|