Skip to content

Commit

Permalink
✅ 인가 코드 반환 후 토큰 발급
Browse files Browse the repository at this point in the history
  • Loading branch information
tjdals4716 committed Jul 29, 2024
1 parent 5e8368c commit 2847d15
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,12 @@ public ResponseEntity<UserDTO> updateNickname(@PathVariable String uid, @Request
UserDTO updatedUser = userService.updateNickname(uid, nickname);
return ResponseEntity.status(HttpStatus.OK).body(updatedUser);
}

// 카카오 로그인 성공 시 인가 코드 반환 엔드포인트 메서드
@PostMapping("/oauth2/code/kakao")
public ResponseEntity<Map<String, String>> getAccessToken(@RequestBody Map<String, String> requestBody) {
String code = requestBody.get("code");
String accessToken = userService.exchangeCodeForToken(code);
return ResponseEntity.ok(Map.of("accessToken", accessToken));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.oauth2Login(oauth2Login ->
oauth2Login
.loginPage("/login")
.defaultSuccessUrl("/oauth2/loginSuccess")
.defaultSuccessUrl("/oauth2/code/kakao")
.failureUrl("/loginFailure")
.userInfoEndpoint(userInfoEndpoint ->
userInfoEndpoint.userService(customOAuth2UserService())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class MangoWaffleeApplication {
Expand All @@ -11,4 +12,8 @@ public static void main(String[] args) {
SpringApplication.run(MangoWaffleeApplication.class, args);
}

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@ public interface UserService {
JWTDTO loginWithOAuth2(OAuth2User oAuth2User);
UserDTO getKakaoUserInfo(String uid);
UserDTO addImageToUser(String uid, MultipartFile image);
String exchangeCodeForToken(String code);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,26 @@
import com.example.MangoWafflee.Entity.UserEntity;
import com.example.MangoWafflee.Repository.UserRepository;
import com.example.MangoWafflee.Global.Config.JWT.JwtTokenProvider;
import com.google.api.client.util.Value;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import com.google.cloud.storage.Storage;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import org.springframework.http.HttpHeaders;

import java.io.IOException;
import java.util.UUID;
Expand All @@ -30,6 +39,7 @@ public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final JwtTokenProvider jwtTokenProvider;
private final Storage storage;
private final RestTemplate restTemplate;

//회원가입
@Override
Expand Down Expand Up @@ -257,5 +267,42 @@ public UserDTO addImageToUser(String uid, MultipartFile image) {
}
return UserDTO.entityToDto(userEntity);
}
}

// 카카오 로그인 성공 시 인가 코드 반환 엔드포인트 메서드
@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;

@Value("${spring.security.oauth2.client.provider.kakao.token-uri}")
private String tokenUri;

@Override
public String exchangeCodeForToken(String code) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("grant_type", "authorization_code");
body.add("client_id", clientId);
body.add("client_secret", clientSecret);
body.add("redirect_uri", redirectUri);
body.add("code", code);

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(body, headers);

ResponseEntity<Map> response = restTemplate.postForEntity(tokenUri, request, Map.class);

if (response.getStatusCode() == HttpStatus.OK) {
Map<String, Object> responseBody = response.getBody();
String accessToken = (String) responseBody.get("access_token");
return accessToken;
} else {
throw new RuntimeException("토큰 발급 실패");
}
}
}

0 comments on commit 2847d15

Please sign in to comment.