본문으로 바로가기
반응형



## 글을 읽기전 참고 해주세요. ##

Kakao Develope에 가입 및 애플리케이션 등록을 하지 않았다면 아래의 링크를 통해 설정 및 확인을 해주세요.

[Spring] Kakao Rest API를 이용해 회원가입을 해보자! - Kako Develope 설정을 하자


리다이렉션을 구현하지 않은 경우 아래의 링크를 눌러주세요.

[Spring] Kakao Rest API를 이용해 회원가입을 해보자! - 리다이렉션을 구현하자!



## 시작 ##

우선, 간단하게 REST API를 사용하는 법에 대해서 알려 드릴게요.


카카오 디벨로퍼스에 들어오신후 REST API 개발 가이드를 눌러주세요.


로그인을 눌러주세요.


조금만 내려주시면 사용자 토큰 받기가 있습니다.

일단, 카카오 Rest API를 통한 간단한 설명을 드리겠습니다.

1. 카카오톡 로그인을 요청하면 카카오 사이트로 이동하고 리다이렉션을 자신의 주소로 한다.

2. 리다이렉션을 하는 경로로 GET 방식으로 개발자에게 code라는 값을 넘긴다.

3. code라는 값은 잠시동안 사용하기 위한 값

4. code를 통해 사용자의 token값을 구할수 있다.

이론적으로 설명은 잘못해서 제가 생각나는대로 적었습니다.


위 설명에 대해서 간단하게 설명을 드리면

POST 방식으로 /oauth/token으로 보내야 한다. 사이트의 호스트는 kauth.kakao.com 이다.

결론 : https://kauth.kakao.com/oauth/token에 POST로 요청을 해라.

값을 요청하기 위해서는 가장 중요할때 파라미터에 어떠한 값을 넘겨야 하는지 꼭 확인 해주세요. (부가적인 설명은 아래 이미지 를 통해 하곘습니다.)


파라미터의 종류는 위 사진을 통해 확인 바랍니다.

아래에 소스 코드를 통해 재차 설명이 될꺼니 여기서는 생략 하겠습니다.



## 로그인 ##




kakao_restapi.java

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
    public JsonNode getAccessToken(String autorize_code) {
        
        final String RequestUrl = "https://kauth.kakao.com/oauth/token";
 
        final List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        
        //포스트 파라미터의 grant_type이라는 명칭에 authorization_code를 추가한다 아래도 동일
        postParams.add(new BasicNameValuePair("grant_type", "authorization_code"));
 
        postParams.add(new BasicNameValuePair("client_id", "자신의 RESTAPI 코드"));
 
        postParams.add(new BasicNameValuePair("redirect_uri", "리다이렉션주소")); //예 : http://아이피:포트/최상위폴더/리다이렉션경로
 
        postParams.add(new BasicNameValuePair("code", autorize_code));
        //기타 설명은 생략 자세히 알고 싶으면 구글링하세요.
        final HttpClient client = HttpClientBuilder.create().build();
 
        final HttpPost post = new HttpPost(RequestUrl);
 
        JsonNode returnNode = null;
 
        try {
 
            post.setEntity(new UrlEncodedFormEntity(postParams));
 
            final HttpResponse response = client.execute(post);
 
            ObjectMapper mapper = new ObjectMapper();
 
            returnNode = mapper.readTree(response.getEntity().getContent());
 
        } catch (UnsupportedEncodingException e) {
 
            e.printStackTrace();
 
        } catch (ClientProtocolException e) {
 
            e.printStackTrace();
 
        } catch (IOException e) {
 
            e.printStackTrace();
 
        } finally {
 
        }
 
        return returnNode;
 
    }
cs

위 소스코드는 이전 게시글을 보고 오셨다면 그대로 두시고 파라미터만 확인 바랄게요.


HomeController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    @RequestMapping(value = "/oauth", produces = "application/json")
    public String kakaoLogin(@RequestParam("code"String code, Model model, HttpSession session) {
        System.out.println("로그인 할때 임시 코드값");
        //카카오 홈페이지에서 받은 결과 코드
        System.out.println(code);
        System.out.println("로그인 후 결과값");
        
        //카카오 rest api 객체 선언
        kakao_restapi kr = new kakao_restapi();
        //결과값을 node에 담아줌
        JsonNode node = kr.getAccessToken(code);
        //결과값 출력
        System.out.println(node);
        //노드 안에 있는 access_token값을 꺼내 문자열로 변환
        String token = node.get("access_token").toString();
        //세션에 담아준다.
        session.setAttribute("token", token);
        
        return "logininfo";
    }
cs

필자는 간단하게 테스트 하기 위해서 출력만하고 필요한 토큰값만 세션에 담아 두었습니다.

home.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>메인 페이지qwe</title>
</head>
<body>
    <a href = "https://kauth.kakao.com/oauth/authorize?client_id=자신의RESTAPI키&redirect_uri=자신의리다이렉션키&response_type=code">
        로그인
    </a>
</body>
</html>
cs

home.jsp는 메인 페이지로 사용 하겠습니다.

자신의 프로젝트에 추가를 하고 싶다면 a태그만 때서 동일하게 사용 하시면 됩니다.


logininfo.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인인포</title>
</head>
<body>
<!-- 세션에서 token을 가져와서 출력한다. -->
    ${sessionScope.token}
</body>
</html>
,!   cs



## 로그인 테스트 결과 ##

여기서 빨간색으로 네모 친 부분은 임시적인 코드

아래의 검은색은 사용자자 받은 토큰



## 로그아웃 ##


HomeController.java

1
2
3
4
5
6
7
8
9
10
    @RequestMapping(value = "/logout", produces = "application/json")
    public String Logout(HttpSession session) {
        //kakao restapi 객체 선언
        kakao_restapi kr = new kakao_restapi();
        //노드에 로그아웃한 결과값음 담아줌 매개변수는 세션에 잇는 token을 가져와 문자열로 변환
        JsonNode node = kr.Logout(session.getAttribute("token").toString());
        //결과 값 출력
        System.out.println("로그인 후 반환되는 아이디 : " + node.get("id"));
        return "redirect:/";
    }    
cs

위 소스코드를 통해 로그아웃을 하기 위한 컨트롤러를 만들게요.


kakao_restapi.java

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
32
33
34
35
36
37
38
    public JsonNode Logout(String autorize_code) {
        final String RequestUrl = "https://kapi.kakao.com/v1/user/logout";
 
        final HttpClient client = HttpClientBuilder.create().build();
 
        final HttpPost post = new HttpPost(RequestUrl);
 
        post.addHeader("Authorization", "Bearer " + autorize_code);
 
        JsonNode returnNode = null;
 
        try {
 
            final HttpResponse response = client.execute(post);
 
            ObjectMapper mapper = new ObjectMapper();
 
            returnNode = mapper.readTree(response.getEntity().getContent());
 
        } catch (UnsupportedEncodingException e) {
 
            e.printStackTrace();
 
        } catch (ClientProtocolException e) {
 
            e.printStackTrace();
 
        } catch (IOException e) {
 
            e.printStackTrace();
 
        } finally {
 
        }
 
        return returnNode;
 
    }
cs

로그아웃을 하기 위한 메소드


logininfo.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인인포</title>
</head>
<body>
    ${sessionScope.token}
    <a href = "/api/logout/">로그아웃</a><br>
</body>
</html>
cs


## 로그아웃 테스트 결과 ##


이상 포스팅을 마무리 하겠습니다.


반응형