[스프링]Spring 카카오 로그인하기 , DB저장

안녕하세요 이번에는 스프링 프레임 워크에서

 

 

카카오 로그인하는 법을 진행 해볼게요~

 

1. dependency   [ pom.xml ] 파일 설정

1
2
3
4
5
6
 
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>
cs

 

일단 gson 의존성을 설정을 해줍니다~

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
<a class="p-2" href="https://kauth.kakao.com/oauth/authorize?
client_id=###############&

// client_id == > 네이버 개발자센터에서 REST API키 를 가져와서 넣어줍니다

redirect_uri=http://localhost:8080/spring/kakao.do&response_type=code"
>

// redirect_uri ==> 카카오 로그인에서 사용할 URL 을 넣어주세요

        <img src="/resources/icon/kakao_login_large_narrow.png" style="height:60px">
                    </a>
                </div>

// 이미지는 구글에 카카오 개발자 에서 무료로 만들어 놓은게 있지만 혹시
필요할지몰라서 첨부해드릴게요
  
 
 
cs

 

kakao.png
0.00MB

2. JSP 페이지 ( 띄어 쓰기 없이 작성해주세요 )

1
2
3
4
5
<a class="p-2" href="https://kauth.kakao.com/oauth/authorize?
client_id=####본인의 키######&
redirect_uri=http://localhost:8080/spring/kakao.do&response_type=code"
>
<img src="/resources/icon/kakao_login_large_narrow.png" style="height:60px"></a>                 
cs

 

 

3. Controller 

JSP 페이지에서 받아온  code 값을 controller 에서 불러와 

access_Token == > 을 생성하고 access_Token 값을 받아서 

userInfo 의 키값을 가져 오겠습니다.

1
2
3
4
5
6
7
8
9
10
11
@RequestMapping(value = "/kakao")
    public String kakaoLogin(@RequestParam(value = "code", required = falseString code, HttpSession session){
        System.out.println("####### " + code);
        
        String access_Token = kaKaoService.getAccessToken(code);
        KakaoVo userInfo = kaKaoService.getuserinfo(access_Token);
       
        
        System.out.println("###access_Token#### : " + access_Token);
        System.out.println("###nickname#### : " + userInfo.getK_name());
        System.out.println("###email#### : " + userInfo.getK_email());
cs

3. access_Token 값 받기위해 전송 !!! 

 

 

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
51
52
53
54
55
56
57
58
 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();
 
            //    POST 요청을 위해 기본값이 false인 setDoOutput을 true로 변경을 해주세요
 
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
 
            //    POST 요청에 필요로 요구하는 파라미터 스트림을 통해 전송
// BufferedWriter 간단하게 파일을 끊어서 보내기로 토큰값을 받아오기위해 전송

            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
            StringBuilder sb = new StringBuilder();
            sb.append("grant_type=authorization_code");
            sb.append("&client_id=### 본인의 key #####");  //본인이 발급받은 key
            sb.append("&redirect_uri=http://localhost:8080/spring/kakao.do");     // 본인이 설정해 놓은 경로
            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;
            }
            System.out.println("response body : " + result+"결과");
 
            //    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) {
 
            e.printStackTrace();
        }
 
        return access_Token;
    }
cs

 

 

4. access_Token 값 읽어오고 db 저장! 

 

 

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public KakaoVo getuserinfo(String access_Token) {
        
        HashMap<String, Object> userInfo = new HashMap<String, Object>();
        
        String requestURL = "https://kapi.kakao.com/v2/user/me";
        
        try {
            URL url = new URL(requestURL); //1.url 객체만들기
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //2.url 에서 url connection 만들기
            conn.setRequestMethod("GET"); // 3.URL 연결구성
            conn.setRequestProperty("Authorization""Bearer " + access_Token);
            
            //키값, 속성 적용
            int responseCode = conn.getResponseCode(); //서버에서 보낸 http 상태코드 반환
            System.out.println("responseCode :" + responseCode+ "여긴가");
            BufferedReader buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            // 버퍼를 사용하여 일근ㄴ것
            String line = "";
            String result = "";
            while ((line = buffer.readLine()) != null) {
                result +=line;
            }
            //readLine()) ==> 입력 String 값으로 리턴값 고정 
            
            System.out.println("response body :" +result);
            
            // 읽엇으니깐 데이터꺼내오기
          JsonParser parser = new JsonParser();
          JsonElement element = parser.parse(result); //Json element 문자열변경
          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 (Exception e) {
           e.printStackTrace();
        }
        
        KakaoVo result = kakaoDao.findkakao(userInfo); 
        // 저장되어있는지 확인
        System.out.println("S :" + result);
        
        if(result ==null) {
            //result null 이면 정보가 저장 안되어있는거라서 저보를 저장.
            kakaoDao.kakaoinsert(userInfo);
            //저장하기위해 repository 로 이동
            return kakaoDao.findkakao(userInfo);
            // 정보 저장후 컨트롤러에 정보를 보냄
            //result 를 리턴으로 보내면 null 이 리턴되므로 위코드를 사용.
        }else {
            return result;
            //정보가 있으므로 result 를 리턴함
        }
        
    }
    
 
    
}
 
 
cs

 

 

5. DAO 설정 Mapper 설정

 

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
@Repository
public class KaKaoDao {
 
    
    private SqlSession sqlSession;
    
    public static final String MAPPER = "ezen.dev.spring.kakao";
    
    @Autowired
    public KaKaoDao(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }
    
    // 정보 저장
    public void kakaoinsert(HashMap<String, Object> userInfo) {
        sqlSession.insert(MAPPER+".insert",userInfo);
    }
 
    // 정보 확인
    public KakaoVo findkakao(HashMap<String, Object> userInfo) {
        System.out.println("RN:"+userInfo.get("nickname"));
        System.out.println("RE:"+userInfo.get("email"));
    
        
        return sqlSession.selectOne(MAPPER+".kakao", userInfo);
    }
cs

 

여기서  카카오 로그인이 정상적으로 되면 닉네임값이랑 , 이메일값이 정상적으로 출력이될거에요

 

값이 없으면 kakaoinsert 메소드 실행하면서 DB (데이터베이스) 에 저장됩니다.

 

5. Mapper sql 문 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
<select id="kakao" parameterType="java.util.HashMap" resultType="kdto">
 
select * from kakao_table where k_name=#{nickname} and k_email=#{email}
 
</select>
 
 
<insert id="insert" parameterType="java.util.HashMap">
 
insert into kakao_table(k_name,k_email)
   values(#{nickname},#{email})
 
</insert>
 
cs

 

6. mybatis 설정 

1
2
3
4
5
6
7
8
9
10
11
12
13
 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
 
<configuration>
 
    <typeAliases>
        <typeAlias alias="memberVo" type="ezen.dev.spring.vo.MemberVo"/>
        <typeAlias alias="kdto" type="ezen.dev.spring.vo.KakaoVo"/>
    </typeAliases>  
 
</configuration>  
cs

 

진행하면 정상적으로 되겠습니다 .감사합니다 !!

 

모두들 화이팅