API

spring 카카오 로그인 api 사용하기 3

rins 2019. 3. 8. 19:39

사용자 정보 받아오는 코드 입니다.

 

이번엔 로그인 정보를 받아오는 코드를 적용하는데 오류가 난다.

401오류, unauthorized error라는데 처음엔 400이더니 코드가 바껴따.

 

이건 bearer에다가 띄어쓰기 실수떄문이었음.

어쨌든 잘 돌아가는코드는

package com.myspring.blog.kakao;

 

@Controller
@RequestMapping("/kakao")
public class kakaoController {
 private Kakao_restapi kakao_restapi=new Kakao_restapi();
 
 @RequestMapping(value="/oauth",method= RequestMethod.GET)
 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/mytest04/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 )throws IOException {
  
  System.out.println("kakao code:"+code);
  JsonNode access_token=kakao_restapi.getKakaoAccessToken(code);
 // access_token.get("access_token");
      //   System.out.println("access_token:" + access_token.get("access_token"));

  JsonNode userInfo = KakaoUserInfo.getKakaoUserInfo(access_token.get("access_token"));

         // Get id
         String member_id = userInfo.get("id").asText();

         String member_name = null;
        
         // 유저정보 카카오에서 가져오기 Get properties
         JsonNode properties = userInfo.path("properties");
         JsonNode kakao_account = userInfo.path("kakao_account");
         member_name = properties.path("nickname").asText(); //이름 정보 가져오는 것
        // email = kakao_account.path("email").asText();
         if(member_name!=null) {
          session.setAttribute("isLogOn",true);
          session.setAttribute("member_id",member_name);        //여기 if문 안에 내용은 다 삭제해도 됩니다. 제 프로젝트에만 필요한 코드임.
         }
         System.out.println("id : " + member_id);    //여기에서 값이 잘 나오는 것 확인 가능함.
         System.out.println("name : " + member_name);
        // System.out.println("email : " + email);
  
         return "redirect:/index.do";
 }
}

 

위에가 컨트롤러 코드임.

이제 토큰가져오는 코드는 앞에랑 똑같은데 다시 보여드릴게요.

 

public class Kakao_restapi {
 public static 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/mytest04/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 (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
 
        return returnNode;
    }
}

이제 사용자 정보 받아오는 코드

 

package com.myspring.blog.kakao;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class KakaoUserInfo {
  public static JsonNode getKakaoUserInfo(JsonNode accessToken) {
   Logger logger = LoggerFactory.getLogger(KakaoUserInfo.class);

         final String RequestUrl = "https://kapi.kakao.com/v2/user/me";
         final HttpClient client = HttpClientBuilder.create().build();
         final HttpPost post = new HttpPost(RequestUrl);
 
         // add header
         post.addHeader("Authorization", "Bearer " + accessToken);  //토큰으로 authorization권한 얻는것.
  
         JsonNode returnNode = null;
 
         try {
             final HttpResponse response = client.execute(post);
             final int responseCode = response.getStatusLine().getStatusCode();
             final String msg=response.getStatusLine().getReasonPhrase();
             System.out.println("\nSending 'POST' request to URL : " + RequestUrl);
             System.out.println("Response Code : " + responseCode);
             System.out.println("Response Code : " + msg);

             //HttpEntity entity = response.getEntity();  이 주석처리 되어있는 코드들은 혹시 오류가 나는 상황이라면 주석 없애고 실행 ㄱㄱ 무슨 오류인지 알려줄거임.
             //String responseString = EntityUtils.toString(entity, "UTF-8");
             //logger.info("responseString----->"+responseString);
             // JSON 형태 반환값 처리
             ObjectMapper mapper = new ObjectMapper();
             returnNode = mapper.readTree(response.getEntity().getContent());  
  
         } catch (ClientProtocolException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             // clear resources
         }
         return returnNode;
     }
}

 

그럼 이렇게 로그인 api사용하는 방법 끝. !! 로그아웃 하는것도 가져올 예정임..

 

 


 

 

'API' 카테고리의 다른 글

spring 카카오 로그인 api 사용하기 2  (0) 2019.03.07
spring 카카오 로그인 api 사용하기 1  (0) 2019.03.07