카카오 로그인 동작 과정
1. 인증 코드 요청
카카오 인증 서버는 해당 사용자에 대한 인가 코드를 발급해 서비스의 redirect_uri에 전달한다.
URL
GET /oauth/authorize?client_id={REST_API_KEY}&redirect_uri={REDIRECT_URI}&response_type=code HTTP/1.1
Host: kauth.kakao.com
코드
@GetMapping("/login/oauth2/code/kakao")
public String getCode(String code) {
return code;
}
2. 인증 토큰 요청
인증 코드를 요청에 실어 보낸다.
코드
@GetMapping("/login/oauth2/code/kakao")
public ResponseEntity<String> getUserInfoByAccessToken(String code) throws JsonProcessingException {
RestTemplate rt = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
//params.add(key, value);
params.add("grant_type", "authorization_code");
params.add("client_id", CLIENT_ID);
params.add("redirect_uri", REDIRECT_URI);
params.add("code", code);
params.add("client_secret", CLIENT_SECRET);
HttpEntity<MultiValueMap<String, String>> kakaoTokenRequest = new HttpEntity<>(params, headers);
ResponseEntity<String> response = rt.exchange(
"https://kauth.kakao.com/oauth/token",
HttpMethod.POST,
kakaoTokenRequest,
String.class
);
return response;
}
3. 사용자(프로필) 정보 가져오기
인증 토큰을 요청에 실어 보낸다.
코드
@GetMapping("/login/oauth2/code/kakao")
public ResponseEntity<String> getUserInfo(String code) throws JsonProcessingException {
RestTemplate rt = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
//params.add(key, value);
params.add("grant_type", "authorization_code");
params.add("client_id", CLIENT_ID);
params.add("redirect_uri", REDIRECT_URI);
params.add("code", code);
params.add("client_secret", CLIENT_SECRET);
HttpEntity<MultiValueMap<String, String>> kakaoTokenRequest = new HttpEntity<>(params, headers);
ResponseEntity<String> response = rt.exchange(
"https://kauth.kakao.com/oauth/token",
HttpMethod.POST,
kakaoTokenRequest,
String.class
);
//response json->object
ObjectMapper objectMapper=new ObjectMapper();
OAuthToken oAuthToken=objectMapper.readValue(response.getBody(),OAuthToken.class);
System.out.println("Kakao access-token: "+ oAuthToken.getAccess_token());
RestTemplate rt2 = new RestTemplate();
HttpHeaders headers2 = new HttpHeaders();
headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
headers.add("Authorization", "Bearer "+oAuthToken.getAccess_token());
ResponseEntity<String> response2 = rt.exchange(
"https://kapi.kakao.com/v2/user/me",
HttpMethod.POST,
kakaoTokenRequest,
String.class
);
return response2;
}
'Programming > Spring' 카테고리의 다른 글
The Custom Authentication Success Handle (0) | 2022.01.20 |
---|---|
OAuth2(3) OAuth2 Client 라이브러리 사용 카카오 로그인 (0) | 2022.01.20 |
OAuth2(1) OAuth2 구성 및 동작 (0) | 2022.01.18 |
CORS (0) | 2021.12.14 |
@DateTimeFormat(pattern = "yyyy-MM-dd") (0) | 2021.09.18 |