|
| 1 | +package umc.codeplay.controller; |
| 2 | + |
| 3 | +import java.util.List; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +import org.springframework.http.*; |
| 7 | +import org.springframework.security.core.authority.SimpleGrantedAuthority; |
| 8 | +import org.springframework.util.LinkedMultiValueMap; |
| 9 | +import org.springframework.util.MultiValueMap; |
| 10 | +import org.springframework.web.bind.annotation.*; |
| 11 | +import org.springframework.web.client.RestTemplate; |
| 12 | +import org.springframework.web.servlet.view.RedirectView; |
| 13 | + |
| 14 | +import lombok.RequiredArgsConstructor; |
| 15 | + |
| 16 | +import umc.codeplay.apiPayLoad.ApiResponse; |
| 17 | +import umc.codeplay.apiPayLoad.code.status.ErrorStatus; |
| 18 | +import umc.codeplay.apiPayLoad.exception.handler.GeneralHandler; |
| 19 | +import umc.codeplay.config.properties.BaseOAuthProperties; |
| 20 | +import umc.codeplay.config.properties.GoogleOAuthProperties; |
| 21 | +import umc.codeplay.config.properties.KakaoOAuthProperties; |
| 22 | +import umc.codeplay.domain.Member; |
| 23 | +import umc.codeplay.domain.enums.SocialStatus; |
| 24 | +import umc.codeplay.dto.MemberResponseDTO; |
| 25 | +import umc.codeplay.jwt.JwtUtil; |
| 26 | +import umc.codeplay.service.MemberService; |
| 27 | + |
| 28 | +@RestController |
| 29 | +@RequestMapping("/oauth") |
| 30 | +@RequiredArgsConstructor |
| 31 | +public class OAuthController { |
| 32 | + |
| 33 | + private final JwtUtil jwtUtil; |
| 34 | + private final RestTemplate restTemplate = new RestTemplate(); |
| 35 | + private final GoogleOAuthProperties googleOAuthProperties; |
| 36 | + private final KakaoOAuthProperties kakaoOAuthProperties; |
| 37 | + private final MemberService memberService; |
| 38 | + |
| 39 | + @GetMapping("/authorize/{provider}") |
| 40 | + public RedirectView redirectToOAuth(@PathVariable("provider") String provider) { |
| 41 | + // CSRF 방어용 state, PKCE(code_challenge)..는 굳이 |
| 42 | + BaseOAuthProperties properties = |
| 43 | + switch (provider) { |
| 44 | + case "google" -> googleOAuthProperties; |
| 45 | + case "kakao" -> kakaoOAuthProperties; |
| 46 | + default -> throw new GeneralHandler(ErrorStatus.INVALID_OAUTH_PROVIDER); |
| 47 | + }; |
| 48 | + |
| 49 | + String url = properties.getUrl(); |
| 50 | + |
| 51 | + RedirectView redirectView = new RedirectView(); |
| 52 | + redirectView.setUrl(url); |
| 53 | + return redirectView; |
| 54 | + } |
| 55 | + |
| 56 | + @GetMapping("/callback/{provider}") |
| 57 | + public ApiResponse<MemberResponseDTO.LoginResultDTO> OAuthCallback( |
| 58 | + @RequestParam("code") String code, @PathVariable("provider") String provider) { |
| 59 | + BaseOAuthProperties properties = |
| 60 | + switch (provider) { |
| 61 | + case "google" -> googleOAuthProperties; |
| 62 | + case "kakao" -> kakaoOAuthProperties; |
| 63 | + default -> throw new GeneralHandler(ErrorStatus.INVALID_OAUTH_PROVIDER); |
| 64 | + }; |
| 65 | + // (1) 받은 code 로 구글 토큰 엔드포인트에 Access/ID Token 교환 |
| 66 | + Map<String, Object> tokenResponse = requestOAuthToken(code, properties); |
| 67 | + |
| 68 | + // (2) 받아온 Access Token(or ID Token)을 통해 사용자 정보 가져오기 |
| 69 | + // String idToken = (String) tokenResponse.get("id_token"); // OIDC |
| 70 | + String accessToken = (String) tokenResponse.get("access_token"); |
| 71 | + Map<String, Object> userInfo = requestOAuthUserInfo(accessToken, properties); |
| 72 | + String email = null; |
| 73 | + String name = null; |
| 74 | + switch (provider) { |
| 75 | + case "google" -> { |
| 76 | + // (3-a) 구글 UserInfo Endpoint 로 이메일, 프로필 등 조회 |
| 77 | + email = (String) userInfo.get("email"); |
| 78 | + name = (String) userInfo.get("name"); |
| 79 | + } |
| 80 | + case "kakao" -> { |
| 81 | + // (3-b) 카카오 UserInfo Endpoint 로 이메일, 프로필 등 조회 |
| 82 | + Map<String, Object> kakaoAccount = |
| 83 | + (Map<String, Object>) userInfo.get("kakao_account"); |
| 84 | + Map<String, Object> kakaoProperties = |
| 85 | + (Map<String, Object>) userInfo.get("properties"); |
| 86 | + email = (String) kakaoAccount.get("email"); |
| 87 | + name = (String) kakaoProperties.get("nickname"); |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + // (4) 우리 DB에서 회원 조회 or 생성 |
| 92 | + Member member = |
| 93 | + memberService.findOrCreateOAuthMember( |
| 94 | + email, name, SocialStatus.valueOf(provider.toUpperCase())); |
| 95 | + |
| 96 | + // (5) JWTUtil 이용해서 Access/Refresh 토큰 발급 |
| 97 | + var authorities = List.of(new SimpleGrantedAuthority("ROLE_" + member.getRole().name())); |
| 98 | + |
| 99 | + String serviceAccessToken = jwtUtil.generateToken(email, authorities); |
| 100 | + String serviceRefreshToken = jwtUtil.generateRefreshToken(email, authorities); |
| 101 | + |
| 102 | + // (6) 최종적으로 JWT(액세스/리프레시)를 프론트에 응답 |
| 103 | + return ApiResponse.onSuccess( |
| 104 | + MemberResponseDTO.LoginResultDTO.builder() |
| 105 | + .email(email) |
| 106 | + .token(serviceAccessToken) |
| 107 | + .refreshToken(serviceRefreshToken) |
| 108 | + .build()); |
| 109 | + } |
| 110 | + |
| 111 | + private Map<String, Object> requestOAuthToken(String code, BaseOAuthProperties properties) { |
| 112 | + HttpHeaders headers = new HttpHeaders(); |
| 113 | + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); |
| 114 | + |
| 115 | + MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); |
| 116 | + params.add("grant_type", "authorization_code"); |
| 117 | + params.add("client_id", properties.getClientId()); |
| 118 | + params.add("client_secret", properties.getClientSecret()); |
| 119 | + params.add("redirect_uri", properties.getRedirectUri()); |
| 120 | + params.add("code", code); |
| 121 | + |
| 122 | + HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers); |
| 123 | + |
| 124 | + ResponseEntity<Map> response = |
| 125 | + restTemplate.postForEntity(properties.getTokenUri(), request, Map.class); |
| 126 | + |
| 127 | + if (response.getStatusCode() == HttpStatus.OK) { |
| 128 | + return response.getBody(); |
| 129 | + } |
| 130 | + throw new GeneralHandler(ErrorStatus.OAUTH_TOKEN_REQUEST_FAILED); |
| 131 | + } |
| 132 | + |
| 133 | + private Map<String, Object> requestOAuthUserInfo( |
| 134 | + String accessToken, BaseOAuthProperties properties) { |
| 135 | + HttpHeaders headers = new HttpHeaders(); |
| 136 | + headers.set("Authorization", "Bearer " + accessToken); |
| 137 | + |
| 138 | + HttpEntity<Void> request = new HttpEntity<>(headers); |
| 139 | + |
| 140 | + ResponseEntity<Map> response = |
| 141 | + restTemplate.exchange( |
| 142 | + properties.getUserInfoUri(), HttpMethod.GET, request, Map.class); |
| 143 | + |
| 144 | + if (response.getStatusCode() == HttpStatus.OK) { |
| 145 | + return response.getBody(); |
| 146 | + } |
| 147 | + throw new GeneralHandler(ErrorStatus.OAUTH_USERINFO_REQUEST_FAILED); |
| 148 | + } |
| 149 | +} |
0 commit comments