Back-end/SpringBoot

[Spring Boot] 차근차근 OAuth 2.0 구현하기 - (3) Access Token 받기

 

[Spring Boot] 차근차근 OAuth 2.0 구현하기 - (2) Code 가져오기

우리에게 친숙한 카카오의 Resource Server에서 데이터를 받아 볼 것이다. 앞선 글에서 봤듯이 🧐 우선 사용자가 카카오를 통해 로그인을 한 후 카카오 Authorization Server에서 Code를 받아오자! 카카오 A

withseungryu.tistory.com

지금까지 Kakao Authorization Server에서 Code를 받아오기까지 성공했다.

 

🔍 이제 code를 받았으니 Resource Server에 접근하기 위한 Access Token(사용자 토큰)을 받아와 보자.

 

우선 카카오 로그인 REST API 문서를 보면,

필수 파라미터 값들을 담아 POST로 요청하고, 요청 성공 시, 응답은 JSON객체로 Redirect URI에 전달된다고 한다.

 

1. Http 객체(Header+Body) 만들기

 

💡 우선 아래 Parameter들을 사용해 POST로 보낼 수 있도록 Body를 만들어주자. 

 

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type","authorization_code");
        params.add("client_id","3a21998518680e26a7713430c60ac0a3");
        params.add("redirect_uri","http://localhost:8081/auth/kakao/callback");
        params.add("code", code);
        params.add("client_secret", "gT8VS2oi38BgR7rKe6cTDOnEF8eu51dh");
  • MultiValueMap 타입은 JSON형식으로 만들어주기에 적합한 타입이다.
//HttpHeader 오브젝트 생성
HttpHeaders headers = new HttpHeaders();
headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
        

//HttpHeader와 HttpBody를 하나의 오브젝트에 담기
HttpEntity<MultiValueMap<String, String>> kakaoTokenRequest =
    new HttpEntity<>(params, headers);
  • HttpHeaders : http의 header를 만들어주는 클래스
  • HttpEntity : Http의 Header와 Body부분을 하나로 저장해주는 클래스

자세한 클래스, 메소드 정보 참고 : https://withseungryu.tistory.com/116

 

 

2. POST 요청하기

 

💡 이렇게 Header를 만들어 아래 URI 형식으로 POST 요청을 해주자.

POST /oauth/token HTTP/1.1
Host: kauth.kakao.com
Content-type: application/x-www-form-urlencoded;charset=utf-8
//POST방식으로 key-value 데이터를 요청(카카오쪽으로)
RestTemplate rt = new RestTemplate(); //http 요청을 간단하게 해줄 수 있는 클래스

//실제로 요청하기
//Http 요청하기 - POST 방식으로 - 그리고 response 변수의 응답을 받음.
ResponseEntity<String> response = rt.exchange(
        "https://kauth.kakao.com/oauth/token",
        HttpMethod.POST,
        kakaoTokenRequest,
        String.class
);
  • RestTemplate : http요청을 간단하게 요청할 수 있도록 해주는 클래스
  • RestTemplate.exchange를 사용해 형식에 맞게 POST 방식으로 요청

이제 Kakao Authorization Server에 요청을 하면 아래와 같이 응답이 올 것이다.

이때 access_token key의 value가 우리가 찾는 Access Token임을 알 수 있다.

자세한 클래스, 메소드 정보 참고 : https://withseungryu.tistory.com/116

 

[Spring Boot] 간단하게 HTTP POST 요청하기

💡 POST 요청이란? 서버에 요청하는 방식 클라이언트가 서버에 요청을 할 때 제공해야하는 자원이 있을 때 Get방식은 요청하는 자원을 URL에 뒤에 보내는 반면 POST방식은 URL에 붙이지 않고 따로 데

withseungryu.tistory.com

 

3. JAVA 객체에 맵핑하기

 

💡 자 이제 ObjectMapper 클래스를 이용해 위 JSON 형식을 각 변수에 저장할 수 있도록 해주자.

 

ObjectMapper  : JSON객체의 key값에 맞는 변수에 저장을 시켜주는 클래스

ObjectMapper objectMapper = new ObjectMapper();
        OAuthToken oauthToken =null;
        //Model과 다르게 되있으면 그리고 getter setter가 없으면 오류가 날 것이다.
        try {
            oauthToken = objectMapper.readValue(response.getBody(), OAuthToken.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
}


//OauthToken.class

@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_expires_in;
}

oauthToken에 POST 요청을 해서 받은 JSON이 저장될 것이다.

 

 

전체 코드 :

String code = this.code;
        //POST방식으로 key-value 데이터를 요청(카카오쪽으로)
        RestTemplate rt = new RestTemplate(); //http 요청을 간단하게 해줄 수 있는 클래스

        //HttpHeader 오브젝트 생성
        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","3a21998518680e26a7713430c60ac0a3");
        params.add("redirect_uri","http://localhost:8081/auth/kakao/callback");
        params.add("code", code);
        params.add("client_secret", "gT8VS2oi38BgR7rKe6cTDOnEF8eu51dh");

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

        //실제로 요청하기
        //Http 요청하기 - POST 방식으로 - 그리고 response 변수의 응답을 받음.
        ResponseEntity<String> response = rt.exchange(
                "https://kauth.kakao.com/oauth/token",
                HttpMethod.POST,
                kakaoTokenRequest,
                String.class
        );


        //Gson Library, JSON SIMPLE LIBRARY, OBJECT MAPPER(Check)
        ObjectMapper objectMapper = new ObjectMapper();
        OAuthToken oauthToken =null;
        //Model과 다르게 되있으면 그리고 getter setter가 없으면 오류가 날 것이다.
        try {
            oauthToken = objectMapper.readValue(response.getBody(), OAuthToken.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

 

참고 : https://developers.kakao.com/docs/latest/ko/kakaologin/rest-api#request-token

 

Kakao Developers

카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다.

developers.kakao.com

 

반응형