|
| 1 | +package inha.gdgoc.domain.user.service; |
| 2 | + |
| 3 | +import org.springframework.beans.factory.annotation.Value; |
| 4 | +import inha.gdgoc.domain.user.repository.UserRepository; |
| 5 | +import jakarta.servlet.http.HttpServletResponse; |
| 6 | +import java.util.Map; |
| 7 | +import lombok.RequiredArgsConstructor; |
| 8 | +import org.springframework.http.HttpEntity; |
| 9 | +import org.springframework.http.HttpHeaders; |
| 10 | +import org.springframework.http.HttpMethod; |
| 11 | +import org.springframework.http.MediaType; |
| 12 | +import org.springframework.http.ResponseEntity; |
| 13 | +import org.springframework.stereotype.Service; |
| 14 | +import org.springframework.util.LinkedMultiValueMap; |
| 15 | +import org.springframework.util.MultiValueMap; |
| 16 | +import org.springframework.web.client.RestTemplate; |
| 17 | + |
| 18 | +@Service |
| 19 | +@RequiredArgsConstructor |
| 20 | +public class GoogleOAuthService { |
| 21 | + |
| 22 | + @Value("${google.client-id}") |
| 23 | + private String clientId; |
| 24 | + |
| 25 | + @Value("${google.client-secret}") |
| 26 | + private String clientSecret; |
| 27 | + |
| 28 | + @Value("${google.redirect-uri}") |
| 29 | + private String redirectUri; |
| 30 | + |
| 31 | + private final UserRepository userRepository; |
| 32 | + |
| 33 | + private final RestTemplate restTemplate = new RestTemplate(); |
| 34 | + |
| 35 | + public void processOAuthLogin(String code, HttpServletResponse response) { |
| 36 | + // 1. code → access token 요청 |
| 37 | + HttpHeaders headers = new HttpHeaders(); |
| 38 | + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); |
| 39 | + |
| 40 | + MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); |
| 41 | + params.add("code", code); |
| 42 | + params.add("client_id", clientId); |
| 43 | + params.add("client_secret", clientSecret); |
| 44 | + params.add("redirect_uri", redirectUri); |
| 45 | + params.add("grant_type", "authorization_code"); |
| 46 | + |
| 47 | + HttpEntity<MultiValueMap<String, String>> tokenRequest = new HttpEntity<>(params, headers); |
| 48 | + ResponseEntity<Map> tokenResponse = restTemplate.postForEntity( |
| 49 | + "https://oauth2.googleapis.com/token", |
| 50 | + tokenRequest, |
| 51 | + Map.class |
| 52 | + ); |
| 53 | + |
| 54 | + String accessToken = (String) tokenResponse.getBody().get("access_token"); |
| 55 | + |
| 56 | + // 2. access token → 사용자 정보 요청 |
| 57 | + HttpHeaders userInfoHeaders = new HttpHeaders(); |
| 58 | + userInfoHeaders.setBearerAuth(accessToken); |
| 59 | + HttpEntity<Void> userInfoRequest = new HttpEntity<>(userInfoHeaders); |
| 60 | + |
| 61 | + ResponseEntity<Map> userInfoResponse = restTemplate.exchange( |
| 62 | + "https://www.googleapis.com/oauth2/v2/userinfo", |
| 63 | + HttpMethod.GET, |
| 64 | + userInfoRequest, |
| 65 | + Map.class |
| 66 | + ); |
| 67 | + } |
| 68 | +} |
0 commit comments