1. 로그인 페이지 만들기!
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
<script src="https://developers.kakao.com/sdk/js/kakao.min.js"></script>
</head>
<body>
<h1>로그인</h1>
<hr>
<form action="/user/login" method="post">
<input type="text" name="username" placeholder="이메일 입력해주세요">
<input type="password" name="password" placeholder="비밀번호">
<button type="submit">로그인</button>
<a href="http://developers.kakao.com/logout"></a>
</form>
<a href="https://kauth.kakao.com/oauth/authorize?client_id={클라이언트키}&redirect_uri={리다이렉트 url}&response_type=code">로그인</a>
<a href="https://kauth.kakao.com/oauth/authorize?response_type=code&client_id={클라이언트아이디}&scope=profile,account_email&state=Z3JNGXqbBZCtif_8D0hz5hWhuAeftMPNUIeCOW4_Kj4%3D&redirect_uri={리다이렉트 url}">동의</a>
<script src="/resources/css/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/resources/css/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="/resources/css/dist/js/adminlte.min.js"></script>
<script src="/resources/js/utils/easy_ui/jquery.easyui.min.js"></script>
</body>
</html>
controller
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.me.genie.service.KakaoService;
@Controller
public class KakaoController {
@Autowired private KakaoService kakaoService;
@RequestMapping("/login")
public String home(@RequestParam(value = "code", required = false) String code, Model model) throws Exception{
System.out.println("#########" + code);
/******************************************************
* 카카오 리턴 값들~
*****************************************************/
String access_Token = "";
if(code != null ) {
access_Token = kakaoService.getAccessToken(code);
}
if(access_Token != "") {
System.out.println("###access_Token#### : " + access_Token);
HashMap<String, Object> userInfo = kakaoService.getUserInfo(access_Token);
System.out.println("###access_Token#### : " + access_Token);
System.out.println("###userInfo#### : " + userInfo.get("email"));
System.out.println("###nickname#### : " + userInfo.get("nickname"));
System.out.println("###profile_image#### : " + userInfo.get("profile_image"));
}
return "home";
}
}
service
package com.me.genie.service;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import org.springframework.stereotype.Service;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
@Service
public class KakaoService {
public String getAccessToken (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();
conn.setRequestMethod("POST");
conn.setDoOutput(true);// POST 요청을 위해 기본값이 false인 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=82693748acf2adcab6a974138e807eea"); // 발급받은 key
sb.append("&redirect_uri=http://localhost:8080/login"); // 설정해 놓은 경로
sb.append("&code=" + authorize_code);
bw.write(sb.toString());
bw.flush();
/***************************************
* 결과 코드가 200이라면 성공
**************************************/
int responseCode = conn.getResponseCode();
System.out.println("responseCode : " + responseCode);
/***************************************
* 결과 데이터 (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();
System.out.println("access_token : " + access_Token);
System.out.println("refresh_token : " + refresh_Token);
/***************************************
* 스트림은 사용 후 꼭 닫아주기!
**************************************/
br.close();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return access_Token;
}
public HashMap<String, Object> getUserInfo (String access_Token) {
/***************************************
* 사용자마다 정보가 다를 수 있기에 HashMap타입으로 선언
**************************************/
HashMap<String, Object> userInfo = new HashMap<String, Object>();
String reqURL = "https://kapi.kakao.com/v2/user/me";
try {
/***************************************
* 요청을 보낼 값 셋팅
**************************************/
URL url = new URL(reqURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
/***************************************
* 요청에 필요한 Header에 포함될 내용
**************************************/
conn.setRequestProperty("Authorization", "Bearer " + access_Token);
/***************************************
*결과 코드가 200이라면 성공
**************************************/
int responseCode = conn.getResponseCode();
System.out.println("responseCode : " + responseCode);
/***************************************
*결과 데이터 (JSON타입의 Response) 메세지 읽어오기
**************************************/
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
String result = "";
while ((line = br.readLine()) != null) {
result += line;
}
br.close();
System.out.println("response body : " + result);
/***************************************
* Gson 라이브러리에 포함된 클래스로 JSON파싱 객체 생성
**************************************/
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 profile_image = properties.getAsJsonObject().get("profile_image").getAsString();
String email = kakao_account.getAsJsonObject().get("email").getAsString();
userInfo.put("nickname", nickname);
userInfo.put("email", email);
userInfo.put("profile_image", profile_image);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return userInfo;
}
}
'프로그래밍' 카테고리의 다른 글
| [jQuery] name*=”value” 선택자 사용법! (0) | 2021.06.08 |
|---|---|
| [SpringBoot] Summernote 이미지 다중 업로드! (0) | 2021.04.06 |
| [SPRING 카카오톡 로그인] #1 개발자사이트 설정 (0) | 2021.02.23 |
| [Google 로그인] #3 백엔드 코드작성! (0) | 2021.02.23 |
| [Google 로그인] #2 FRONT 코드작성! (0) | 2021.02.16 |