Skip to content

Commit

Permalink
✅ 드디어 성공
Browse files Browse the repository at this point in the history
  • Loading branch information
tjdals4716 committed Jul 31, 2024
1 parent 988f912 commit a1e1bf8
Show file tree
Hide file tree
Showing 8 changed files with 115 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -115,14 +115,14 @@ public ResponseEntity<UserDTO> updateNickname(@PathVariable String uid, @Request
}

// 카카오 로그인 성공 시 호출되는 엔드포인트 (GET)
@GetMapping("/callback")
@GetMapping("/oauth2/code/kakao")
public ResponseEntity<JWTDTO> kakaoCallback(@RequestParam String code) {
JWTDTO jwtDto = userService.loginWithOAuth2(code);
return ResponseEntity.ok(jwtDto);
}

// 카카오 로그인 성공 시 호출되는 엔드포인트 (POST)
@PostMapping("/callback")
@PostMapping("/oauth2/code/kakao")
public ResponseEntity<JWTDTO> kakaoLoginPost(@RequestBody OAuth2CodeDTO codeDTO) {
JWTDTO jwtDto = userService.loginWithOAuth2(codeDTO.getCode());
return ResponseEntity.ok(jwtDto);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.example.MangoWafflee.Global.Config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.example.MangoWafflee.Global.Config;

import org.springframework.beans.factory.annotation.Value;
import jakarta.annotation.PostConstruct;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
Expand All @@ -25,14 +25,16 @@ public class CustomOAuth2LoginSuccessHandler implements AuthenticationSuccessHan

private static final Logger logger = LoggerFactory.getLogger(CustomOAuth2LoginSuccessHandler.class);

@Value("${spring.security.oauth2.client.registration.kakao.client-id}")
private String clientId;
private final KakaoOAuthProperties kakaoOAuthProperties;

@Value("${spring.security.oauth2.client.registration.kakao.client-secret}")
private String clientSecret;
public CustomOAuth2LoginSuccessHandler(KakaoOAuthProperties kakaoOAuthProperties) {
this.kakaoOAuthProperties = kakaoOAuthProperties;
}

@Value("${spring.security.oauth2.client.registration.kakao.redirect-uri}")
private String redirectUri;
@PostConstruct
public void logKakaoOAuthSettings() {
logger.info("Kakao OAuth 설정 값 - clientId : {}, clientSecret : {}, redirectUri : {}", kakaoOAuthProperties.getClientId(), kakaoOAuthProperties.getClientSecret(), kakaoOAuthProperties.getRedirectUri());
}

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Expand All @@ -42,7 +44,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo

String code = request.getParameter("code");
logger.info("인가 코드 : {}", code);
logger.info("리다이렉트 URI : {}", redirectUri);
logger.info("리다이렉트 URI : {}", kakaoOAuthProperties.getRedirectUri());

if (code != null) {
String tokenEndpoint = "https://kauth.kakao.com/oauth/token";
Expand All @@ -53,9 +55,9 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "authorization_code");
params.add("client_id", clientId);
params.add("client_secret", clientSecret);
params.add("redirect_uri", redirectUri);
params.add("client_id", kakaoOAuthProperties.getClientId());
params.add("client_secret", kakaoOAuthProperties.getClientSecret());
params.add("redirect_uri", kakaoOAuthProperties.getRedirectUri());
params.add("code", code);

logger.info("토큰 요청 파라미터 (위치 : CustomOAuth2LoginSuccessHandler) : {}", params);
Expand All @@ -80,4 +82,4 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo

response.sendRedirect("/");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ public class JwtTokenProvider {
@Value("${jwt.expiration}")
private Long expiration;

@PostConstruct
public void logKakaoOAuthSettings() {
logger.info("JWT 설정 값 - secret : {}, expiration : {}", secret, expiration);
}

private Key key;

//활성화된 토큰을 저장하는 맵
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.example.MangoWafflee.Global.Config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "spring.security.oauth2.client.registration.kakao")
public class KakaoOAuthProperties {
private String clientId;
private String clientSecret;
private String redirectUri;

// getters and setters
public String getClientId() {
return clientId;
}

public void setClientId(String clientId) {
this.clientId = clientId;
}

public String getClientSecret() {
return clientSecret;
}

public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}

public String getRedirectUri() {
return redirectUri;
}

public void setRedirectUri(String redirectUri) {
this.redirectUri = redirectUri;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,4 @@ public class MangoWaffleeApplication {
public static void main(String[] args) {
SpringApplication.run(MangoWaffleeApplication.class, args);
}

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
60 changes: 38 additions & 22 deletions src/main/java/com/example/MangoWafflee/Service/UserServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import com.example.MangoWafflee.Entity.UserEntity;
import com.example.MangoWafflee.Repository.UserRepository;
import com.example.MangoWafflee.Global.Config.JWT.JwtTokenProvider;
import com.example.MangoWafflee.Global.Config.KakaoOAuthProperties;
import com.google.api.client.util.Value;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -37,6 +39,7 @@ public class UserServiceImpl implements UserService {
private final JwtTokenProvider jwtTokenProvider;
private final Storage storage;
private final RestTemplate restTemplate;
private final KakaoOAuthProperties kakaoOAuthProperties;

//회원가입
@Override
Expand Down Expand Up @@ -168,52 +171,65 @@ public JWTDTO getUserWithTokenInfo(String uid, String token) {
return new JWTDTO(token, UserDTO.entityToDto(userEntity), remainingTime);
}

@Value("${spring.security.oauth2.client.registration.kakao.client-id}")
private String clientId;

@Value("${spring.security.oauth2.client.registration.kakao.client-secret}")
private String clientSecret;

@Value("${spring.security.oauth2.client.registration.kakao.redirect-uri}")
private String redirectUri;
@PostConstruct
public void logKakaoOAuthSettings() {
logger.info("Kakao OAuth 설정 값 - clientId : {}, clientSecret : {}, redirectUri : {}", kakaoOAuthProperties.getClientId(), kakaoOAuthProperties.getClientSecret(), kakaoOAuthProperties.getRedirectUri());
}

//카카오 인가 코드로 액세스 토큰 요청
// 카카오 인가 코드로 액세스 토큰 요청
public String getAccessToken(String code) {
String url = "https://kauth.kakao.com/oauth/token";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "authorization_code");
params.add("client_id", clientId);
params.add("redirect_uri", redirectUri);
params.add("client_id", kakaoOAuthProperties.getClientId());
params.add("redirect_uri", kakaoOAuthProperties.getRedirectUri());
params.add("code", code);
params.add("client_secret", clientSecret);
params.add("client_secret", kakaoOAuthProperties.getClientSecret());

logger.info("액세스 토큰 요청 URL: {}", url);
logger.info("액세스 토큰 요청 헤더: {}", headers);
logger.info("액세스 토큰 요청 파라미터: {}", params);

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
try {
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
Map<String, Object> responseBody = response.getBody();
logger.info("Response from Kakao: {}", responseBody);
return responseBody != null ? (String) responseBody.get("access_token") : null;
if (responseBody != null) {
String accessToken = (String) responseBody.get("access_token");
logger.info("액세스 토큰을 성공적으로 가져왔습니다: {}", accessToken);
return accessToken;
} else {
logger.error("액세스 토큰을 가져오는데 실패했습니다. 응답 본문이 비어있습니다.");
return null;
}
} catch (HttpClientErrorException e) {
logger.error("액세스 토큰을 가져오는 중 오류가 발생하였습니다. (위치 : getAccessToken) : {}", e.getMessage());
logger.error("Response body, (위치 : getAccessToken) : {}", e.getResponseBodyAsString());
logger.error("액세스 토큰을 가져오는 중 오류가 발생하였습니다. (위치: getAccessToken): {}", e.getMessage());
logger.error("응답 본문 (위치: getAccessToken): {}", e.getResponseBodyAsString());
throw e;
}
}

//액세스 토큰으로 사용자 정보 요청
private Map<String, Object> getUserInfo(String accessToken) {
// 액세스 토큰으로 사용자 정보 요청
public Map<String, Object> getUserInfo(String accessToken) {
String url = "https://kapi.kakao.com/v2/user/me";
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + accessToken);
HttpEntity<String> entity = new HttpEntity<>(headers);
try {
ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.GET, entity, Map.class);
return response.getBody();
Map<String, Object> responseBody = response.getBody();
if (responseBody != null) {
logger.info("사용자 정보를 성공적으로 가져왔습니다 : {}", responseBody);
return responseBody;
} else {
logger.error("사용자 정보를 가져오는데 실패했습니다. 응답 본문이 비어있습니다.");
return null;
}
} catch (HttpClientErrorException e) {
logger.error("사용자 정보 가져오는 중 오류가 발생했습니다. (위치 : getUserInfo) : " + e.getMessage());
logger.error("Response body, (위치 : getUserInfo) : {}", e.getResponseBodyAsString());
logger.error("사용자 정보를 가져오는 중 오류가 발생했습니다. (위치: getUserInfo): {}", e.getMessage());
logger.error("응답 본문 (위치: getUserInfo): {}", e.getResponseBodyAsString());
throw e;
}
}
Expand Down Expand Up @@ -332,4 +348,4 @@ public UserDTO getUserById(Long userId) {
.orElseThrow(() -> new RuntimeException("유저의 id가 " + userId + "인 사용자를 찾을 수 없습니다"));
return UserDTO.entityToDto(userEntity);
}
}
}
8 changes: 4 additions & 4 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ spring:
jpa:
show-sql: false
hibernate:
ddl-auto: update
ddl-auto: create
properties:
hibernate:
format_sql: false
Expand Down Expand Up @@ -49,6 +49,6 @@ google:
credentials:
base64key: ${BUCKET_INCODING_KEY}

logging:
level:
org.springframework.security: DEBUG
#logging:
# level:
# org.springframework.security: DEBUG

0 comments on commit a1e1bf8

Please sign in to comment.