본문 바로가기
Dev/SpringBoot

17. [SpringBoot] 스프링부트 카카오 로그인하기 구현(따라치기만하면됨)(2)

by VIPeveloper 2020. 7. 24.
반응형

서론

1편에 이어 2편도 제작하려 합니다. 1편은 하단 링크를 참고하시면 됩니다.

 

16. [SpringBoot] 스프링부트 카카오 로그인하기 구현(따라치기만하면됨)(1)

서론 카카오 소셜로그인을 구현하려고 구글링을 이곳 저곳 해봤는데,, 다들 너무 어렵고, 내가 아는것이 맞나,, 싶을정도로 하나도 모르겠었습니다. 그러다 우연히 https://master-gromit.tistory.com/11?ca

dkyou.tistory.com

저번 시간에는 인증 코드를 요청하고 카카오 서버를 거쳐 인증코드를 가져오는 첫번째 단계까지 확인했습니다.

이번에는 인증코드로 토큰 요청을 하고, 토큰을 받아오는 과정까지 진행해보려 합니다.

본론

access_token을 가져오기 위해서는 다음과 같이 4개의 조건이 필요합니다. grant_type은 string으로 고정되어있으니 해결했고, client_id랑 redirect_url은 이전에 설정해놓은거 그대로 가져오면 되겠네요.

마지막으로 코드도 파라메타로 넘겨 받았으니 짱 쉽게 넣으면 됩니다.

public JsonNode getKakaoAccessToken(String code) {
        final String RequestUrl = "https://kauth.kakao.com/oauth/token"; // Host
        final List<NameValuePair> postParams = new ArrayList<NameValuePair>();

        postParams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        postParams.add(new BasicNameValuePair("client_id", "REST API KEY!!!")); // REST API KEY
        postParams.add(new BasicNameValuePair("redirect_uri", "http://localhost:8080/kakao/callback")); // 리다이렉트 URI
        postParams.add(new BasicNameValuePair("code", code)); // 로그인 과정중 얻은 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);
            final int responseCode = response.getStatusLine().getStatusCode();

            System.out.println("\nSending 'POST' request to URL : " + RequestUrl);
            System.out.println("Post parameters : " + postParams);
            System.out.println("Response Code : " + responseCode);

            // JSON 형태 반환값 처리
            ObjectMapper mapper = new ObjectMapper();

            returnNode = mapper.readTree(response.getEntity().getContent());

        } catch (IOException e) {
            e.printStackTrace();
        }

        return returnNode;
    }

이분 코드를 분석하면서 NameValuePair 객체또한 알게 되었네요. 다시한번 감사드립니다. 귀찮으신 분들을 위해 공부한거 조금 정리해드립니다.

BasicNameValuePair

BasicNameValuePair 클래스의 목적은 1개의 데이터를 전달하기 위한 것이므로 Name/Value값 하나만 저장하는 구조로 설계되어 있다.

리스트에 담아서 http통신하기 위한 목적으로 만들어진 객체 같습니다.

try - catch에 담아서 통신한 후 가져온 객체를 JsonNode에 담아서 리턴하면 끝입니다!

@Controller
@RequestMapping("/kakao")
public class KakaoController {

    @GetMapping(value="/oauth")
    public String kakaoConnect() {

        StringBuffer url = new StringBuffer();
        url.append("https://kauth.kakao.com/oauth/authorize?");
        url.append("client_id=" + "받은 Client_id");
        url.append("&redirect_uri=http://localhost:8080/kakao/callback");
        url.append("&response_type=code");

        return "redirect:" + url.toString();
    }

    @RequestMapping(value="/callback",produces="application/json",method= {RequestMethod.GET, RequestMethod.POST})
    public String kakaoLogin(@RequestParam("code")String code, RedirectAttributes ra, HttpSession session, HttpServletResponse response, Model model)throws IOException {

        System.out.println("kakao code:"+code);
        JsonNode access_token = getKakaoAccessToken(code);
		}
		public JsonNode getKakaoAccessToken(String code) {
        final String RequestUrl = "https://kauth.kakao.com/oauth/token"; // Host
        final List<NameValuePair> postParams = new ArrayList<NameValuePair>();

        postParams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        postParams.add(new BasicNameValuePair("client_id", "...")); // REST API KEY
        postParams.add(new BasicNameValuePair("redirect_uri", "http://localhost:8080/kakao/callback")); // 리다이렉트 URI
        postParams.add(new BasicNameValuePair("code", code)); // 로그인 과정중 얻은 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);
            final int responseCode = response.getStatusLine().getStatusCode();

            System.out.println("\nSending 'POST' request to URL : " + RequestUrl);
            System.out.println("Post parameters : " + postParams);
            System.out.println("Response Code : " + responseCode);

            // JSON 형태 반환값 처리
            ObjectMapper mapper = new ObjectMapper();

            returnNode = mapper.readTree(response.getEntity().getContent());

        } catch (IOException e) {
            e.printStackTrace();
        }

        return returnNode;
    }
}

서버 실행 후 클릭해봤을 때 response 200 코드가 떳을 때 정말 기뻣던 기억이 있네요,, 다시한번 감사드립니다.

 

이로써 인증토큰 요청과 인증토큰을 전달받는 과정까지 진행해보았습니다.

다음에는 이 인증받은 정보를 바탕으로 사용자 정보요청하는 과정을 포스팅해보겠습니다.

반응형