엑세스 토큰을 header와 body 나눠서 볼 수 있다.  ▶ response.getBody();  

 

 

[UserController]

//카카오 로그인 
@GetMapping("/auth/kakao/callback")
public @ResponseBody String kakaoCallback(String code) { //데이터를 리턴해주는 컨트롤러 함수

    // POST방식으로 key=value 데이터를 요청 (카카오쪽으로)
    RestTemplate rt = new RestTemplate();  // http요청을 쉽게 할 수 있는 라이브러리

    // HttpHeaders 오브젝트 생성
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");

    // HttpBody 오브젝트 생성
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", "authorization_code"); // 값을 변수화하는게 낫다
    params.add("client_id", "e801f6365d439407c6f6764bf7dc64ef");
    params.add("redirect_uri", "http://localhost:8000/auth/kakao/callback");
    params.add("code", code);

    // HttpHeaders 와 HttpBody 를 하나의 오브젝트에 담기
    HttpEntity<MultiValueMap<String, String>> kakaoTokenRequest =
            new HttpEntity<>(params, headers); //바디 데이터와 와 헤더값을 가지는 entity가 된다

    // Http 요청하기 - POST방식으로 그리고 response 변수의 응답 받음
    ResponseEntity<String> response = rt.exchange(
            "https://kauth.kakao.com/oauth/token", //토큰 발급 요청 주소
            HttpMethod.POST, //요청 메서드 post
            kakaoTokenRequest,
            String.class // 응답받을 타입
    );

    return response.getBody();
}

 

return response.getBody(); 으로 리턴하면 엑세스 토큰정보를 볼 수 있다.

 

 

 

엑세스 토큰

 

 

 

 

 

이제 위의 정보들을 모두 OAuthToken 객체에 담는다. 

 

 

 

 

[OAuthToken]

package com.cos.blog.model;

import lombok.Data;

@Data
public class OAuthToken {
	private String access_token;
	private String token_type;
	private String refresh_token;
	private int expires_in;
	private String scope;
	private int refresh_token_expries_in;
}

 

*주의할 점

파싱할때 변수명이 틀리면 오류나고 @Data를 붙여야 @getter @setter 가져다 쓸수있음

 

 

 

 

 

제이슨 데이터에서 자바오브젝트로 변경하기

 

[UserController]

 

제이슨 데이터를 자바에서 처리하기 위해 자바오브젝트로 바꾸려면 ObjectMapper 라이브러리에 담는다. 

// 제이슨을 ObjectMapper 라이브러리에 담는다. 
    ObjectMapper objectMapper = new ObjectMapper();
    OAuthToken oauthToken = null;
        try {
            oauthToken = objectMapper.readValue(response.getBody(), OAuthToken.class);
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    System.out.println("카카오 엑세스 토큰 : "+oauthToken.getAccess_token());

    return response.getBody();
}

 

readValue() 를 사용하면 oauthToken 객체를 제이슨 데이터에서 자바obj 으로 변경

oauthToken = objectMapper.readValue(response.getBody(), OAuthToken.class);

: response.getBody() ▶ OAuthToken.class 에 담는다.

 

 

System.out.println("카카오 엑세스 토큰 : "+oauthToken.getAccess_token());

카카오 엑세스 토큰을 잘 받았음.

 

 

 

 

[UserController]

//카카오 로그인 
@GetMapping("/auth/kakao/callback")
public @ResponseBody String kakaoCallback(String code) { //데이터를 리턴해주는 컨트롤러 함수

    // POST방식으로 key=value 데이터를 요청 (카카오쪽으로)
    RestTemplate rt = new RestTemplate();  // http요청을 쉽게 할 수 있는 라이브러리

    // HttpHeaders 오브젝트 생성
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");

    // HttpBody 오브젝트 생성
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", "authorization_code"); // 값을 변수화하는게 낫다
    params.add("client_id", "e801f6365d439407c6f6764bf7dc64ef");
    params.add("redirect_uri", "http://localhost:8000/auth/kakao/callback");
    params.add("code", code);

    // HttpHeaders 와 HttpBody 를 하나의 오브젝트에 담기
    HttpEntity<MultiValueMap<String, String>> kakaoTokenRequest =
            new HttpEntity<>(params, headers); //바디 데이터와 와 헤더값을 가지는 entity가 된다

    // Http 요청하기 - POST방식으로 그리고 response 변수의 응답 받음
    ResponseEntity<String> response = rt.exchange(
            "https://kauth.kakao.com/oauth/token", //토큰 발급 요청 주소
            HttpMethod.POST, //요청 메서드 post
            kakaoTokenRequest,
            String.class // 응답받을 타입
    );
    
    // 제이슨을 ObjectMapper 라이브러리에 담는다. 
    ObjectMapper objectMapper = new ObjectMapper();
    OAuthToken oauthToken = null;
        try {
            oauthToken = objectMapper.readValue(response.getBody(), OAuthToken.class);
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    System.out.println("카카오 엑세스 토큰 : "+oauthToken.getAccess_token());

    return response.getBody();
}

 

 

반응형
LIST

+ Recent posts