๐
๋ ์ง
2025-05-13
๐ ํ์ต ๋ด์ฉ
โ
1. ๊ฐ์
- ์ธ๊ฐ ์ฝ๋ ์์ ํ ํ ํฐ ๋ฐ๊ธ๊น์ง ์๋ฃ๋์ด์ผ ์นด์นด์ค ๋ก๊ทธ์ธ์ด ์ ์์ ์ผ๋ก ์๋ฃ๋จ.
- ํ ํฐ์ ์ด์ฉํด ์ฌ์ฉ์ ์ ๋ณด ์์ฒญ ๋ฐ ๋ก๊ทธ์ธ ์ฒ๋ฆฌ๊ฐ ๊ฐ๋ฅํด์ง.
application/x-www-form-urlencoded
๋ฐฉ์์ผ๋ก POST
์์ฒญ ์ํ.
โ
2. ํ ํฐ ๋ฐ๊ธ API ์ ๋ณด
ํญ๋ชฉ | ๋ด์ฉ |
---|
URL | https://kauth.kakao.com/oauth/token |
METHOD | POST |
์ธ์ฆ ๋ฐฉ์ | ์์ (์ธ๊ฐ ์ฝ๋ ๊ธฐ๋ฐ) |
โ
3. ์์ฒญ ํค๋ & ๋ฐ๋ ๊ตฌ์ฑ
๐ ์์ฒญ ํค๋
Content-Type: application/x-www-form-urlencoded;charset=utf-8
๐ ์์ฒญ ๋ฐ๋
ํ๋ผ๋ฏธํฐ | ์ค๋ช
| ํ์ |
---|
grant_type | authorization_code ๋ก ๊ณ ์ | โ
|
client_id | ์นด์นด์ค ์ฑ์ REST API ํค | โ
|
redirect_uri | ๋ฑ๋กํ ๋ฆฌ๋๋ ์
URI | โ
|
code | ์ธ๊ฐ ์ฝ๋ (/callback ์ผ๋ก ์ ๋ฌ๋จ) | โ
|
โ
4. ์๋ต ์์ (JSON)
{
"access_token": "F1BbYx6oI2MX-JgjKG5nZzEwj4Ga3F5cAAAAAQoNIZYAAAGWx0ENspQkbXeV0h_w",
"token_type": "bearer",
"refresh_token": "wl-wC3GxMbnS4MrinNDANVI2OVxBYEiwAAAAAgoNIZYAAAGWx0ENrJQkbXeV0h_w",
"expires_in": 21599,
"scope": "account_email profile_image profile_nickname",
"refresh_token_expires_in": 5183999
}
5๏ธโฃ Spring Boot ์ฝ๋
@GetMapping("/callback")
public String callback(@RequestParam("code") String code){
log.info("GET /kakao/callback..." + code);
String url = "https://kauth.kakao.com/oauth/token";
HttpHeaders header = new HttpHeaders();
header.add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "authorization_code");
params.add("client_id", CLIENT_ID);
params.add("redirect_uri", REDIRECT_URI);
params.add("code", code);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, header);
RestTemplate rt = new RestTemplate();
ResponseEntity<KakaoTokenResponse> response = rt.exchange(
url, HttpMethod.POST, entity, KakaoTokenResponse.class
);
this.kakaoTokenResponse = response.getBody();
System.out.println(response);
return "redirect:/kakao/main";
}
โ
KakaoTokenResponse DTO
@Data
private static class KakaoTokenResponse {
public String access_token;
public String token_type;
public String refresh_token;
public int expires_in;
public String scope;
public int refresh_token_expires_in;
}
โ
๋ก๊ทธ์ธ ํ ๋ฉ์ธ ํ์ด์ง ์ฐ๊ฒฐ
@GetMapping("/main")
public void main(){
log.info("GET /kakao/main...");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>๋ฉ์ธ ํ์ด์ง</h1>
</body>
</html>
๐ฅ ์ ๋ฆฌ
- ์ธ๊ฐ ์ฝ๋๋ฅผ ๋ฐ์ ํ ํ ํฐ ๋ฐ๊ธ๊น์ง ์๋ฃํด์ผ ์นด์นด์ค ๋ก๊ทธ์ธ์ด ์ ์ ์ฒ๋ฆฌ๋๋ค.
- ์๋ต JSON์ DTO๋ก ๋งคํํ์ฌ ์ฝ๊ฒ ์ฌ์ฉํ ์ ์๋ค.
- ํ ํฐ์ ๋ฐ์์๋ค๋ฉด ์ด์ ์ฌ์ฉ์ ์ ๋ณด ์์ฒญ์ ํตํด ์ค์ ์ฌ์ฉ์ ๋ฐ์ดํฐ๋ฅผ ํ์ฉ ๊ฐ๋ฅ.
๐ ์ฐธ๊ณ ์๋ฃ