Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- scheduled
- programmers
- 브라우저
- @Scheduled
- URLRewirte
- eGov
- Oracle
- 물리적주소
- ua-parser
- Java
- Login
- Was
- TailMe
- 접근장치
- window10
- dbms
- Tomcat
- WebtoB
- web server
- AES
- 알고리즘
- 암호화
- WINDOW11
- mysql
- User-Agent
- Firebase
- db
- 개발자도구
- JEUS
- FCM
Archives
- Today
- Total
HD
[KAKAO] 계정 로그인 API 연동 (2) 본문
반응형
1. AccessToken 처리
/**
* KAKAO AccessToken 처리
* @param authorize_code
* @return
*/
@Override
public String getKakaoAccessToken (String authorize_code) {
String access_Token = "";
//String refresh_Token = "";
String reqURL = "https://kauth.kakao.com/oauth/token";
try {
URL url = new URL(reqURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//POST 요청을 위해 기본값이 false인 setDoOutput을 true로
conn.setRequestMethod("POST");
conn.setDoOutput(true);
//POST 요청에 필요로 요구하는 파라미터 스트림을 통해 전송
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
StringBuilder sb = new StringBuilder();
sb.append("grant_type=authorization_code");
sb.append("&client_id=client_id");
sb.append("&redirect_uri=redirect_uri");
sb.append("&code="+authorize_code);
sb.append("&state=url Parameter");
bw.write(sb.toString());
bw.flush();
//결과 코드가 200이라면 성공
int responseCode = conn.getResponseCode();
//요청을 통해 얻은 JSON타입의 Response 메세지 읽어오기
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
String result = "";
while ((line = br.readLine()) != null) {
result += line;
}
//Gson 라이브러리에 포함된 클래스로 JSON파싱 객체 생성
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result);
access_Token = element.getAsJsonObject().get("access_token").getAsString();
//refresh_Token = element.getAsJsonObject().get("refresh_token").getAsString();
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
return access_Token;
}
2. KAKAO 유저정보
/**
* KAKAO USER INFO
* @param access_Token
*/
@Override
public void getKaKaoUserInfo (String access_Token) {
//요청하는 클라이언트마다 가진 정보가 다를 수 있기에 HashMap타입으로 선언
HashMap<String, Object> kakaoUserInfo = new HashMap<>();
String reqURL = "https://kapi.kakao.com/v2/user/me";
try {
URL url = new URL(reqURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
//요청에 필요한 Header에 포함될 내용
conn.setRequestProperty("Authorization", "Bearer " + access_Token);
//int responseCode = conn.getResponseCode();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
String result = "";
while ((line = br.readLine()) != null) {
result += line;
}
System.out.println("response body : " + result);
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result);
JsonObject properties = element.getAsJsonObject().get("properties").getAsJsonObject();
JsonObject kakao_account = element.getAsJsonObject().get("kakao_account").getAsJsonObject();
String nickname = properties.getAsJsonObject().get("nickname").getAsString();
String email = kakao_account.getAsJsonObject().get("email").getAsString();
String id = "KAKAO_"+element.getAsJsonObject().get("id").toString();
kakaoUserInfo.put("nickname", nickname);
kakaoUserInfo.put("email", email);
kakaoUserInfo.put("id", id);
System.out.println("login Controller : " + kakaoUserInfo);
} catch (IOException e) {
e.printStackTrace();
}
}
3.Controller
/**
* sns Login
*/
@RequestMapping( "/index" )
public String view(
ModelMap model ) {
String kakaoUrl = "https://kauth.kakao.com/oauth/authorize?client_id=client_id&redirect_uri=redorect_uri&response_type=code&state=url_parameter";
model.addAttribute( "kakaoUrl", kakaoUrl );
return "/index";
}
/**
* KAKAO Login
* @param code
* @throws IOException
*/
@RequestMapping( "/kakaoLogin" )
public void kakaoLogin(
@RequestParam("code") String code,
HttpServletResponse response) throws IOException {
String access_Token = snsLoginService.getAccessToken(code);
String referer = (String)request.getHeader("REFERER")!=null? (String)request.getHeader("REFERER") : "http://localhost:8080";
snsLoginService.getUserInfo(access_Token);
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
//Login Popup창 닫고 page referer url로 새로고침
out.println("<script>window.close(); opener.parent.location="+"'"+referer+"'"+";</script>");
out.flush();
}
4. index.jsp
<a id="custom-login-btn" href="javascript:void(0);" onclick="window.open('${kakaoUrl}','kakaoLogin','width=430,height=500,location=no,status=no,scrollbars=yes');"">
<img src="//mud-kage.kakao.com/14/dn/btqbjxsO6vP/KPiGpdnsubSq3a0PHEGUK1/o.jpg" width="300"/>
</a>
반응형
'API > KAKAO' 카테고리의 다른 글
[KAKAO] 계정 로그인 API 연동 (1) (0) | 2019.10.24 |
---|
Comments