티스토리 뷰

[1] 카카오 REST API 로그인

 


1 ) 코드 받기 Copy URL


카카오톡 로그인 기능은 일반적인 OAuth 인증의 과정을 거친다. 

우선 로그인 버튼 클릭 시 코드를 받아와서 사용자 토큰을 얻을 준비를 해야한다. 

[Request]

GET /oauth/authorize?client_id={app_key}&redirect_uri={redirect_uri}&response_type=code HTTP/1.1
Host: kauth.kakao.com

[Response]

HTTP/1.1 302 Found
Content-Length: 0
Location: {redirect_uri}?code={authorize_code}

카카오 OAuth 서버에서 크로스 도메인 요청을 허용하고 있지 않기 때문에, URL 링크로 바로 이동시키거나 URL로 Redirect 시켜서 코드를 받았다. 

app_key는 앱 생성시 받은 REST API Key를 입력하면 되고, redirect_url은 기본정보에 입력한 리다이렉트 path를 입력한다. 




GET 방식 요청 URL은 다음과 같다.

https://kauth.kakao.com/oauth/authorize?client_id= REST API 키 &redirect_uri=http://localhost:8080/kakaologin&response_type=code 



로그인 버튼을 클릭했을때 위의 링크로 이동하면 아래의 카카오톡 로그인 화면이 뜬다.

카카오톡 계정/PASSWORD를 입력하면 URI의 Redirect Path로 리다이렉트되며 code를 반환한다. 

컨트롤러에서 다음과 같이 코드를 얻을 수 있다. 




2) 사용자 토큰 받기


코드를 얻은 다음, 이제부터 코드를 이용하여 실제로 API를 호출할 수 있는 사용자 토큰(Access Token, Refresh Token)을 받아 올 수 있다.


[Request]

POST /oauth/token HTTP/1.1
Host: kauth.kakao.com
설명필수
grant_typeauthorization_code로 고정O
client_id앱 생성시 발급 받은 REST API 키.O
redirect_uri코드가 리다이렉트 된 URI. 
설정 > 일반 >  > 사이트 도메인에서 설정한 각각의 도메인에 설정 > 일반 >  > Redirect Path 를 붙인 URI.
O
code위 코드 받기에서 발급 받은 인증된 코드.



[Response]

응답 바디는 JSON 객체로 아래 값을 포함합니다.

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
{
    "access_token":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "token_type":"bearer",
    "refresh_token":"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
    "expires_in":43199,
    "scope":"Basic_Profile"
}

요청 결과로 API를 호출할 때 사용하는 access_token과 해당 토큰의 만료 시간(초 단위), 또한 토큰을 갱신 할 수 있는 refresh_token을 받습니다.



사용자 토큰은 얻은 code를 이용해서 POST 방식으로 요청해야한다. 뷰에서 Ajax로 요청하거나 컨트롤러에서 요청하면 된다.

다음은 컨트롤러에서 요청하기 위한 함수이다. 


public static JsonNode getAccessToken(String autorize_code){ 

    final String RequestUrl = "https://kauth.kakao.com/oauth/token";


    final List<NameValuePair> postParams = new ArrayList<NameValuePair>();

    postParams.add(new BasicNameValuePair("grant_type", "authorization_code"));

    postParams.add(new BasicNameValuePair("client_id", RestApiKey));    // REST API KEY

    postParams.add(new BasicNameValuePair("redirect_uri", Redirect_URI));    // 리다이렉트 URI

    postParams.add(new BasicNameValuePair("code", autorize_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 (UnsupportedEncodingException e) {

      e.printStackTrace();

    } catch (ClientProtocolException e) {

      e.printStackTrace();

    } catch (IOException e) {

      e.printStackTrace();

    } finally {

        // clear resources

    }

   

    return returnNode;

}


컨트롤러에서 JsonNode의 트리 형태로 토큰을 받아서 제대로 출력되는지 확인한다. 


import org.codehaus.jackson.JsonNode;


JsonNode jsonToken = Kakao.getAccessToken(code);

System.out.println("JSON 반환 : " + jsonToken.get("access_token"));




댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함