기본 설정하기

기초 설정하기 참고 링크 : https://innovation123.tistory.com/181#3.%20Controller-1

카카오 공식문서 : https://developers.kakao.com/docs/latest/ko/kakaologin/rest-api


실제 사용되는 부분

 

1. 앱설정 - 요약정보 (A)

2. 제품설정 - 카카오 로그인 (B)


기초 흐름도


 

1. 카카오 공식문서 - 인가 코드 받기 부분

 

controller

//카카오 DOC 공식 요청 예제
https://kauth.kakao.com/oauth/authorize?response_type=code&client_id=${REST_API_KEY}&redirect_uri=${REDIRECT_URI}

상단은 카카오 인가코드 받기 예제코드로 이것을 model에 값을 넣어 활용하여 jsp 페이지로 넘겨준다.

@RequestMapping("/loginPage")
	public String loginPage(Model model) {
		String id = "(A)의 REST API 키"; 
        //5e.....96d의 경우
        //String id = "5e.....96d"; 
		String url = "(B)의 redirect:url";
       
        //http://localhost:8080/helloPage인경우
        //String url = "http://localhost:8080/helloPage";

	    String KakaoURL = "https://kauth.kakao.com/oauth/authorize?client_id=" + id + "&redirect_uri=" + url + "&response_type=code";
		model.addAttribute("KakaoURL", KakaoURL);
		return "member/loginPage";
	}

 

loginPage.jsp

 

<form action="login" method="post"onsubmit="return submitLoginForm();" style="margin-left: 40px;">
	<table>
		<tr>
			<td>아이디<br> <input name="member_name" placeholder="id"value=""><br>
			</td>
		</tr>
		<tr>
			<td>비밀번호 <br> <input name="member_password"type="password" placeholder="Password" value=""><br>
			</td>
		</tr>
        <!--만일 에러가 난다면 csrf 부분 지우고 진행할것 -->
		<tr>
			<td><input type="hidden" name="${_csrf.parameterName}"value="${_csrf.token}" /></td>
		</tr>
	</table>
		<button class="form_btn" style="margin-left: -10px;">로그인하기</button>
			<a class="form_btn" style="margin-left: -10px; display: inline-block; padding: 10px; background-color: #f0f0f0; text-decoration: none; color: black;" href="${KakaoURL}">Kakao 로그인
            </a>	
			<a class="form_btn" style="margin-left: -10px; display: inline-block; padding: 10px; background-color: #f0f0f0; text-decoration: none; color: black;"href="">naver 로그인
            </a>	
</form>

 

 

 

 

2. 카카오 공식문서 - 토큰 받기 부분 ~ 실제 요소 추출

@RequestMapping("/kakaologinPage")
	public String kakaologin(@RequestParam String code, Model model,HttpSession session) throws JsonMappingException, JsonProcessingException {
		System.out.println("code = " + code);

        // 1. header 생성
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=utf-8");

        // 2. body 생성
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "authorization_code"); //건드리지않기!
        params.add("client_id", "(A)의 REST API 키"); //(A)의 API키
        params.add("redirect_uri", "(B)의 redirect:url"); //아까 (B)의 URL
        params.add("code", code); // 내가 받아온 인증코드

        // 3. header + body
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, httpHeaders);

        // 4. http 요청하기
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(
        	    "https://kauth.kakao.com/oauth/token",
        	    HttpMethod.POST,
        	    httpEntity,
        	    String.class
        	);
        System.out.println("response = " + response);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(response.getBody().toString());
        String accessToken = rootNode.path("access_token").asText();
        
        String responseBody = response.getBody().toString();
// 토큰 받기 끝
// 사용자 정보 추출
     // 6. 사용자 정보 요청을 위한 헤더 설정
     HttpHeaders userInfoHeaders = new HttpHeaders();
     
     userInfoHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
     userInfoHeaders.set("Authorization", "Bearer " + accessToken);


     // 7. 사용자 정보 요청
     HttpEntity<String> userInfoRequest = new HttpEntity<String>(null, userInfoHeaders);
     ResponseEntity<String> userInfoResponse = restTemplate.exchange(
             "https://kapi.kakao.com/v2/user/me",
             HttpMethod.GET,
             userInfoRequest,
             String.class
     );

     // 8. 사용자 정보 출력
     String userInfoJson = userInfoResponse.getBody();
     System.out.println("UserInfo Response = " + userInfoJson);

     objectMapper = new ObjectMapper();
     try {
         JsonNode rootNode2 = objectMapper.readTree(userInfoJson);
         // "kakao_account" 객체 내의 "email" 필드를 찾습니다.
         String email = rootNode2.path("kakao_account").path("email").asText();
         System.out.println("Email: " + email);
         session.setAttribute("userEmail", email);
     } catch (IOException e) {
         e.printStackTrace();
     } 
        return "redirect:/kakaologin";
	}

1. 헤더 생성

 

  • HttpHeaders 객체를 생성하여 HTTP 요청에 사용될 헤더를 설정합니다.
  • Content-Type 헤더를 application/x-www-form-urlencoded;charset=utf-8로 설정하여, 요청 본문이 URL 인코딩된 폼 데이터임을 나타냅니다.

2. 요청 본문 생성

  • Auth 토큰을 요청하기 위한 파라미터를 설정합니다.
  • grant_type에는 OAuth 2.0에서 정의된 인증 코드 방식(authorization_code)을 사용합니다.
  • client_id, redirect_uri, code에는 각각 애플리케이션의 API 키, 인증 코드를 받기 위해 설정한 리다이렉트 URI, 인증 과정에서 얻은 코드를 설정합니다.

3. HTTP 요청 생성

  • 설정한 헤더와 요청 본문을 포함하는 HttpEntity 객체를 생성합니다.

4. 토큰 요청

  • RestTemplate을 사용하여 카카오 OAuth 서버에 토큰 요청을 합니다.
  • 요청의 결과로 받은 응답을 콘솔에 출력합니다.
  • 실제 성공시 다음과 같은 화면을 볼수 있다.

//1번 ~ 4번의 과정은 해당 코드를 대신하기 위함
curl -v -X POST "https://kauth.kakao.com/oauth/token" \
 -H "Content-Type: application/x-www-form-urlencoded" \
 -d "grant_type=authorization_code" \
 -d "client_id=${REST_API_KEY}" \
 --data-urlencode "redirect_uri=${REDIRECT_URI}" \
 -d "code=${AUTHORIZE_CODE}"

5. 액세스 토큰 추출

  • 응답 본문(JSON)을 파싱하여 액세스 토큰을 추출합니다.

6. 사용자 정보 요청을 위한 헤더 설정

  • 사용자 정보를 요청하기 위한 새로운 HttpHeaders 객체를 생성하고, Authorization 헤더에 액세스 토큰을 포함시킵니다.

7. 사용자 정보 요청

  • 설정한 헤더를 사용하여 사용자 정보를 요청합니다.

8. 사용자 정보 출력 및 세션 저장

  • 응답으로 받은 사용자 정보(JSON)를 콘솔에 출력하고, 이메일 주소를 추출

 

 

+ Recent posts