일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- kotiln const
- java 백준 1509
- nodejs rabbitmq
- 백준 1504 java
- java 1509
- ipfs singletone
- kotiln functional interface
- 백준 특정한 최단 경로
- java 팩토리얼 개수
- spring mongodb
- kotiln const val
- 백준 연결요소 자바
- javav 1676
- mongodb lookup
- Java Call By Refernce
- 전략 패턴이란
- 자바 1676
- rabbitmq 싱글톤
- 백준 2252 줄세우기
- 안정해시
- spring mongoTemplate
- spring mongodb switch
- go
- java 파티
- ipfs bean
- spring mongoTemplate switch
- Spring ipfs
- java 1238
- 익명 객체 @transactional
- 자바 백준 팩토리얼 개수
Archives
- Today
- Total
공부 흔적남기기
Spring MVC Kakao소셜 로그인 방법과 과정 본문
728x90
반응형
Spring MVC에서 Kakao 소셜 로그인 하는 과정부터 간단히 보면
- html 단에서 location.href를 통해 카카오 로그인 인증 코드를 받을 수 있는 URL로 이동한다.
- 코드를 받으면 미리 설정해 놓은 redirect_url로 돌아오는데 이때 Controller로 이 url을 잡는다.
- 잡았을때 @RequestParam에서 code가 들어가있다 code를 저장한다.
- code를 이용해 HttpRequest 를 만들어 kakao인증 페이지에 보낸다.
- 만약 code가 인증에 성공했다면 접근할 수 있는 JWT 토큰을 부여받는다.
- 다음 요청에 JWT토큰을 이용해 HttpRequest를 보낸다.
- 토큰이 알맞으면 카카오 로그인을 한 user의 정보를 받는다.
이제 순서대로 코드로 살펴보면
html 단에서 location.href를 통해 카카오 로그인 인증 코드를 받을 수 있는 URL로 이동한다.
<button id="login-kakao-btn"
class="w-100 btn btn-secondary btn-lg"
onclick="location.href='https://kauth.kakao.com/oauth/authorize?client_id=카카오devloper에서 받은 RestApiKey&redirect_uri=서버 IP주소/user/kakao/callback&response_type=code'">
카카오 로그인
</button>
코드를 받으면 미리 설정해 놓은 redirect_url로 돌아오는데 이때 Controller로 이 url을 잡는다.
잡았을때 @RequestParam에서 code가 들어가있다 code를 저장한다.
@GetMapping("/user/kakao/callback")
public String kakaoLogin(@RequestParam String code, HttpServletRequest request) throws JsonProcessingException {
// authorizedCode: 카카오 서버로부터 받은 인가 코드
log.info("Hello here!");
memberService.kakaoLogin(code, request);
return "redirect:/";
}
code를 이용해 HttpRequest 를 만들어 kakao인증 페이지에 보낸다.
private String getAccessToken(String code) throws JsonProcessingException {
// HTTP Header 생성
HttpHeaders headers = new HttpHeaders();
headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
// HTTP Body 생성
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("grant_type", "authorization_code");
body.add("client_id", "카카오developer에서 받은 restApiKey");
body.add("redirect_uri", "http://서버IP/user/kakao/callback");
body.add("code", code);
// HTTP 요청 보내기
HttpEntity<MultiValueMap<String, String>> kakaoTokenRequest = new HttpEntity<>(body, headers);
RestTemplate rt = new RestTemplate();
ResponseEntity<String> response = rt.exchange(
"https://kauth.kakao.com/oauth/token",
HttpMethod.POST,
kakaoTokenRequest,
String.class
);
// HTTP 응답 (JSON) -> 액세스 토큰 파싱
String responseBody = response.getBody();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(responseBody);
return jsonNode.get("access_token").asText();
}
다음 요청에 JWT토큰을 이용해 HttpRequest를 보낸다.
토큰이 알맞으면 카카오 로그인을 한 user의 정보를 받는다.
private KakaoUserInfoDto getKakaoUserInfo(String accessToken) throws JsonProcessingException {
// HTTP Header 생성
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + accessToken);
headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
// HTTP 요청 보내기
HttpEntity<MultiValueMap<String, String>> kakaoUserInfoRequest = new HttpEntity<>(headers);
RestTemplate rt = new RestTemplate();
ResponseEntity<String> response = rt.exchange(
"https://kapi.kakao.com/v2/user/me",
HttpMethod.POST,
kakaoUserInfoRequest,
String.class
);
String responseBody = response.getBody();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(responseBody);
Long id = jsonNode.get("id").asLong();
String nickname = jsonNode.get("properties")
.get("nickname").asText();
String email = jsonNode.get("kakao_account")
.get("email").asText();
return new KakaoUserInfoDto(id, nickname, email);
}
이후 값을 받아서 강제 로그인 처리를 해주어 세션에 저장시키고 쿠키를 던져주면 된다! JWT토큰을 만들어서 보내줘도 되고 로그인 과정은 자유!
728x90
반응형
'web study > Spring' 카테고리의 다른 글
JPA N+1문제 트러블슈팅 (0) | 2022.04.05 |
---|---|
SpringBoot Redis를 활용한 Socket 통신(WebSocket, Stomp) (0) | 2022.03.09 |
SpringSecurity 로그인 실패시 Http 400보내는 방법 (0) | 2022.02.13 |
Spring MVC (0) | 2022.02.06 |
DispatcherServlet의 간단한 과정 (0) | 2022.01.30 |