웅겹살의 프로그래밍 삼매경

[Spring Boot] 카카오로그인 Token값 받기까지 기록 본문

Spring

[Spring Boot] 카카오로그인 Token값 받기까지 기록

웅겹사r☆ 2021. 2. 15. 10:30

 

 

 

카카오로그인 작업중
oauth2로 추후 변경예정

구글 페이스북 등등 다해버리자

RestAPI같은 방식으로 회사에서 많이해서그런지 익숙하다

역시 RestTemplate 사용하는 방식이 편하다

 

카카오로그인 토큰요청까지 작업함

필요한 내용 주석달았음

 

 

카카오에서 제공하는 로그인버튼 넣었더니 간지작살난다

    @GetMapping("/auth/kakao/callback")
    public @ResponseBody String kakaoCallback(String code){

        // POST방식으로 key=value 데이터 요청(카카오쪽으로 찌른다)
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers  = new HttpHeaders();
        headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");

        // HttpBody 오브젝트 생성
        // 일단 param들 변수화 안함.. 추후 예정
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "authorization_code");
        params.add("client_id", "카카오에서 제공받은 KEY 입력");
        params.add("redirect_uri", "http://localhost:8000/auth/kakao/callback");
        params.add("code", code);

        // HttpHeader와 HttpBody를 하나의 오브젝트로 담는다
        HttpEntity<MultiValueMap<String,String>> kakaoTokenRequest =
                new HttpEntity<>(params, headers);

        // 실제요청
        ResponseEntity<String> response = restTemplate.exchange(
                "https://kauth.kakao.com/oauth/token",
                HttpMethod.POST,
                kakaoTokenRequest,
                String.class
        );

        System.out.println("response : ");
        System.out.println(response.toString());

        return "kakao token response : " + response;
    }

내일쯤 카카오로그인 완료 예상

Comments