티스토리 뷰

KaKao Developers에서 애플리케이션 생성하고 RSET API키 값, Redirect Url 설정 등등은 구글링하면 쉽게 찾을 수 있으니 PASS

 

java/com/kakaoLogin/controller/HomeController.java

 

@Controller
public class HomeController {
    @RequestMapping(value="/")
    public String index() {
        return "index";
    }
    
    @RequestMapping(value="/login")
    public String login() {
        return "index";
    }
}

 


 

localhost:9000에 접속하면

결과

 

하지만 로그인 버튼을 누르면,,

 

날 놀리는 듯한 단무지가 있다. index.html을 확인해보자.

 


 

templates/index.html

<!DOCTYPE html>
<html xmlns:c="http://www.w3.org/1999/XSL/Transform">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<body>
<c:if test="${userId eq null}">
    <a href="https://kauth.kakao.com/oauth/authorize
    ?response_type=code
    &client_id={REST_API_KEY}
    &redirect_uri=https://localhost:9000/login">
        <img src="/img/kakao_login_medium_narrow.png">
    </a>
</c:if>
<c:if test="${userId ne null}">
    <h1>로그인 성공입니다</h1>
</c:if>
</body>
</html>

href 안에 적힌 주소를 주소창에 복붙하면 잘 뜨는데, 뭐가 문젠지 한참 해맸는데, 저 공백이 문제였다...

<a href="https://kauth.kakao.com/oauth/authorize?&client_id={REST_API_KEY}&redirect_uri=http://localhost:9000/login&response_type=code">

위처럼 공백을 지워주니 로그인 화면이 잘 떴다... 너무 허무해

 


로그인 화면

 

동의하고 계속하기 누르면

 

access token, refresh token을 발급받고,

내 닉네임과 이메일을 얻어오는 것 까지 성공했다.

 

 


index.html 설정

로그아웃 버튼 추가

<!DOCTYPE html>
<html xmlns:c="http://www.w3.org/1999/XSL/Transform">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<body>
<c:if test="${userId eq null}">
    <a href="https://kauth.kakao.com/oauth/authorize?&client_id=0d31644dbd291f49ff894526df554d2d&redirect_uri=http://localhost:9000/login&response_type=code">
        <img src="/img/kakao_login_medium_narrow.png">
    </a>
</c:if>
<c:if test="${userId ne null}">
    <h1>로그인 성공입니다</h1>
    <input type="button" value="로그아웃" onclick="location.href='/logout'">
</c:if>
</body>
</html>

 


java/com/kakaoLogin/controller/HomeController.java

@Controller
public class HomeController {
    
    @Autowired
    private KaKaoApi kakao;
    
    @RequestMapping(value="/")
    public String index() {
        return "index";
    }

    @RequestMapping(value="/login")
    public String login(@RequestParam("code") String code, HttpSession session) {
    
        // Access Token 얻기
        String access_token = kakao.getAccessToken(code);
        // 사용자 정보 얻기
        HashMap<String ,Object> userInfo = kakao.getUserInfo(access_token);
        System.out.println("login Controller = " + userInfo);
        System.out.println("access_token = " + access_token);
        
        // 아래에 원하는 사용자 정보를 session.setAttribute로 저장
        if(userInfo.get("email") != null) {
            session.setAttribute("userId", userInfo.get("email"));
            session.setAttribute("nick_name", userInfo.get("nickname"));
            // 로그아웃 처리 시 사용할 토큰
            session.setAttribute("access_Token", access_token);
        }
        return "index";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        kakao.kakaoLogout((String)session.getAttribute("access_Token"));
        session.removeAttribute("access_Token");
        session.removeAttribute("userId");
        System.out.println("로그아웃 성공!");
        return "index";
    }
}

 

  • access_token
    • service/KaKaoApi.java의 getAccessToken()에 login 호출 시 RequestParam("code")로 받아온 authorizeCode를 넣어서 받아온다.
  • userInfo
    • 위에서 받아온 access_token을 이용해 service/KaKaoApi.java의 getUserInfo()에서 받아온다.
  • session
    • setAttribute로 유저 정보를 설정

java/com/kakaoLogin/service/KaKaoApi.java

 

getAccessToken()

public String getAccessToken(String authorizeCode) {
        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();

            // HttpURLConnection 설정 값 세팅
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);

            // buffer 스트림 객체 값 세팅 후 요청
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
            StringBuilder sb = new StringBuilder();
            sb.append("grant_type=authorization_code");
            sb.append("&client_id={REST_API_KEY}");  // 발급받은 REST API 키
            sb.append("&redirect_uri=http://localhost:9000/login");  // 설정한 Redirect Uri
            sb.append("&code=" + authorizeCode);  // 파라미터로 받은 authorizaCode
            bw.write(sb.toString());
            bw.flush();

            int responseCode = conn.getResponseCode();
            System.out.println("[GetAccessToken] responseCode = " + responseCode);

            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = "";
            String result = "";
            
            // Response Body 확인
            while ((line = br.readLine()) != null) {
                result += line;
            }
            System.out.println("[GetAccessToken] response body = " + result);

            // gson 라이브러리 필요
            JsonParser parser = new JsonParser();
            JsonElement element = parser.parse(result);

			// access 토큰과 refresh 토큰 파싱
            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;
    }

 


 

getUserInfo()

public HashMap<String, Object> getUserInfo(String access_Token) {

        HashMap<String, Object> userInfo = 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();
            System.out.println("[GetUserInfo] responseCode = " + responseCode);

            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line = "";
            String result = "";

		// Response Body를 저장
            while((line = br.readLine()) != null) {
                result += line;
            }

            JsonParser parser = new JsonParser();
            JsonElement element = parser.parse(result);
		
		// properties와 kakao_account를 파싱해서 저장
            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();

            userInfo.put("nickname", nickname);
            userInfo.put("email", email);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return userInfo;
    }
  • 유저의 정보는 요청하는 클라이언트마다 다를 수 있기 때문에 HaspMap 으로 선언
  • HomeController 의 login()에서 getUserInfo 메소드를 통해 받아온 유저 정보에 email 정보가 있을 때 세션에 토큰과 이메일을 등록

kakaoLogout()

public void kakaoLogout(String access_Token) {
        String reqURL = "https://kapi.kakao.com/v1/user/logout";
        try {
            URL url = new URL(reqURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization", "Bearer " + access_Token);

            int responseCode = conn.getResponseCode();
            System.out.println("[Logout] responseCode = " + responseCode);
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String result = "";
            String line = "";

            while((line = br.readLine()) != null) {
                result += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

https://kapi.kakao.com/v1/user/logout 경로를 통해 헤더에 Authorization: "Bearer {access_Token}"을 포함하여 요청하면 로그아웃을 수행한 클라이언트의 아이디를 반환.

 

 

 

일단 기본적인 카카오 로그인은 구현했고, 이제부터 진짜 시작이다......

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
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
글 보관함