반응형
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
카카오api 작업도중 위 오류가 발생했다.
구글링을 해보니 인증서가 신뢰하지 않은(?) 인증서라 그렇다고 한다.
야매로 SSL인증서를 무시하는 코드를 작성하려고 한다.!
간단하다.
url 호출하기전에 아래와 같은 코드를 작성해주자
* 참고로 코드는 jsp에서 작성한것으로 HTML코드에 java언어를 삽입하였습니다
<%@ page import="java.security.cert.X509Certificate" %>
<%@ page import="javax.net.ssl.HttpsURLConnection" %>
<%@ page import="javax.net.ssl.SSLContext" %>
<%@ page import="javax.net.ssl.TrustManager" %>
<%@ page import="javax.net.ssl.X509TrustManager" %>
<%@ page import="javax.net.ssl.HostnameVerifier" %>
<%@ page import="javax.net.ssl.SSLSession" %>
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {return null;}
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session){
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
위 코드를 try 구문 안, url호출하기전에 넣어주면 된다.
수정된 코드는 다음과 같다!
- 수정 전 코드
<%@page import="org.json.JSONObject"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.io.BufferedWriter"%>
<%@page import="java.io.OutputStreamWriter"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.net.HttpURLConnection"%>
<%@page import="java.net.URL"%>
try{
URL url = new URL("https://kauth.kakao.com/oauth/token");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("grant_type=authorization_code&client_id="+client_id+"&redirect_uri="+redirect_uri+"&code="+code);
bw.flush();
bw.close();
osw.close();
os.close();
if (con.getResponseCode() != 200) {
con.disconnect();
error_reason = "인증이 실패하였습니다.<br>" + con.getResponseMessage();
} else {
InputStream is = con.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String ln;
while ((ln = br.readLine()) != null) {
sb.append(ln);
}
br.close();
isr.close();
is.close();
con.disconnect();
JSONObject json = new JSONObject(sb.toString());
String token_type = json.has("token_type") ? json.getString("token_type") : null;
String access_token = json.has("access_token") ? json.getString("access_token") : null;
int expires_in = json.has("expires_in") ? json.getInt("expires_in") : -1;
if (access_token == null || access_token.equals("")) {
error_reason = "인증토큰을 가져오지 못했습니다.";
} else {
url = new URL("https://kapi.kakao.com/v2/user/me");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", "Bearer "+access_token);
if (con.getResponseCode() != 200) {
con.disconnect();
error_reason = "인증정보를 가져오지 못했습니다.<br>" + con.getResponseMessage();
} else {
is = con.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
sb = new StringBuilder();
while ((ln = br.readLine()) != null) {
sb.append(ln);
}
br.close();
isr.close();
is.close();
con.disconnect();
json = new JSONObject(sb.toString());
String id = json.has("id") ? json.getString("id") : null;
JSONObject properties = json.has("properties") ? new JSONObject(json.getString("properties")) : null;
String name = properties != null && properties.has("nickname") ? properties.getString("nickname") : null;
if (id == null || id.equals("") || id.equals("0")) {
error_reason = "인증이 실패하였습니다.<br>사용자 정보 읽기 실패";
} else {
session.setAttribute("kakao_access_token", access_token);
session.setAttribute("kakao_id", id);
session.setAttribute("kakao_name", name==null?"":name);
error_reason = "OK";
}
}
}
}
} catch (Exception e) {
out.println(e);
}
- 수정 후 코드
<%@page import="org.json.JSONObject"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.io.BufferedWriter"%>
<%@page import="java.io.OutputStreamWriter"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.net.HttpURLConnection"%>
<%@page import="java.net.URL"%>
<%@ page import="java.security.cert.X509Certificate" %>
<%@ page import="javax.net.ssl.HttpsURLConnection" %>
<%@ page import="javax.net.ssl.SSLContext" %>
<%@ page import="javax.net.ssl.TrustManager" %>
<%@ page import="javax.net.ssl.X509TrustManager" %>
<%@ page import="javax.net.ssl.HostnameVerifier" %>
<%@ page import="javax.net.ssl.SSLSession" %>
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@include file="./config.jsp"%>
<%
String error = request.getParameter("error");
String error_description = request.getParameter("error_description");
String error_reason = request.getParameter("error_reason");
String code = request.getParameter("code");
String state = request.getParameter("state");
if (error != null && !error.equals("")) {
error_reason = "인증이 취소되었습니다.";
} else {
try{
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {return null;}
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session){
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
URL url = new URL("https://kauth.kakao.com/oauth/token");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("grant_type=authorization_code&client_id="+client_id+"&redirect_uri="+redirect_uri+"&code="+code);
bw.flush();
bw.close();
osw.close();
os.close();
if (con.getResponseCode() != 200) {
con.disconnect();
error_reason = "인증이 실패하였습니다.<br>" + con.getResponseMessage();
} else {
InputStream is = con.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String ln;
while ((ln = br.readLine()) != null) {
sb.append(ln);
}
br.close();
isr.close();
is.close();
con.disconnect();
JSONObject json = new JSONObject(sb.toString());
String token_type = json.has("token_type") ? json.getString("token_type") : null;
String access_token = json.has("access_token") ? json.getString("access_token") : null;
int expires_in = json.has("expires_in") ? json.getInt("expires_in") : -1;
if (access_token == null || access_token.equals("")) {
error_reason = "인증토큰을 가져오지 못했습니다.";
} else {
url = new URL("https://kapi.kakao.com/v2/user/me");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", "Bearer "+access_token);
if (con.getResponseCode() != 200) {
con.disconnect();
error_reason = "인증정보를 가져오지 못했습니다.<br>" + con.getResponseMessage();
} else {
is = con.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
sb = new StringBuilder();
while ((ln = br.readLine()) != null) {
sb.append(ln);
}
br.close();
isr.close();
is.close();
con.disconnect();
json = new JSONObject(sb.toString());
String id = json.has("id") ? json.getString("id") : null;
JSONObject properties = json.has("properties") ? new JSONObject(json.getString("properties")) : null;
String name = properties != null && properties.has("nickname") ? properties.getString("nickname") : null;
if (id == null || id.equals("") || id.equals("0")) {
error_reason = "인증이 실패하였습니다.<br>사용자 정보 읽기 실패";
} else {
session.setAttribute("kakao_access_token", access_token);
session.setAttribute("kakao_id", id);
session.setAttribute("kakao_name", name==null?"":name);
error_reason = "OK";
}
}
}
}
} catch (Exception e) {
out.println(e);
}
}
%>
반응형
댓글