Skip to content

Commit

Permalink
Merge pull request #19 from 9oormthon-univ/fix/#18
Browse files Browse the repository at this point in the history
[fix] 카카오 로그인 response 수정
  • Loading branch information
m3k0813 authored Nov 23, 2024
2 parents 0800dfa + 16d0c25 commit 7db04b7
Show file tree
Hide file tree
Showing 12 changed files with 39 additions and 485 deletions.
1 change: 0 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ dependencies {
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
runtimeOnly 'com.h2database:h2'

// Spring Security
implementation 'org.springframework.boot:spring-boot-starter-webflux'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public User findOrCreateUser(KakaoUserResponseDto kakaoUser) {
User newUser = new User(
kakaoUser.id(), // ID는 자동 생성
kakaoUser.properties().nickname(),
"0", // 새로운 유저의 경우 뽑기 횟수 => 0
0, // 새로운 유저의 경우 뽑기 횟수 => 0
kakaoUser.properties().thumbnailImage(), // 카카오 프로필 이미지
null, // 프로필 별자리 이름 (별자리)
null // 프로필 별자리 uri (별자리)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Component
@Configuration
@RequiredArgsConstructor
@EnableWebSecurity
Expand Down Expand Up @@ -66,7 +67,6 @@ public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws
// Public endpoint 허용
httpSecurity.authorizeHttpRequests(authorizeHttpRequests ->
authorizeHttpRequests
.requestMatchers("/").permitAll().anyRequest().authenticated() // 모든 경로인가
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.requestMatchers("http://localhost:8080/api/v1/oauth/kakao/callback").permitAll() // 인증 없이 허용
.requestMatchers("/api/v1/account/signup").permitAll()
Expand All @@ -88,7 +88,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedOriginPatterns(List.of("https://your-frontend-domain.com")); // TODO: 프론트엔드 도메인으로 변경
corsConfiguration.setAllowedOriginPatterns(List.of("*")); //
corsConfiguration.setAllowedHeaders(List.of("*"));
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedMethods(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,37 @@
package com.goormthon.bookduchilseong.global.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SwaggerConfig {

@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.openapi("3.0.0")
.components(new Components())
.info(apiInfo());
.openapi("3.0.0")
.components(new Components().addSecuritySchemes("bearerAuth", createBearerAuth()))
.info(apiInfo())
.addSecurityItem(new SecurityRequirement().addList("bearerAuth"));
}

private SecurityScheme createBearerAuth() {
return new SecurityScheme()
.name("Authorization")
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT");
}

private Info apiInfo() {
return new Info()
.title("북두칠성 API")
.description("북두칠성 api")
.version("1.0.0");
.title("북두칠성 API")
.description("북두칠성 API 설명")
.version("1.0.0");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,9 @@ public ResponseEntity<KakaoLoginUrlResponseDto> kakaoLogin() {
}
)
@GetMapping("/kakao/callback")
public ResponseEntity<KakaoLoginResponseDto> kakaoCallback(@RequestParam("code") String code) {
public com.goormthon.bookduchilseong.global.apiPayload.ApiResponse<?> kakaoCallback(@RequestParam("code") String code) {
KakaoLoginResponseDto response = oAuthService.processKakaoCallback(code);
return ResponseEntity.ok(response);
// return ResponseEntity.ok(response);
return com.goormthon.bookduchilseong.global.apiPayload.ApiResponse.onSuccess(response);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,8 @@

@Builder
public record KakaoLoginResponseDto(
@NonNull Long accountId,
@NonNull String accessToken,
@NonNull String refreshToken,
@Schema(description = "신규 유저 여부.")
boolean isNewUser
@NonNull String refreshToken
) {

}
Original file line number Diff line number Diff line change
Expand Up @@ -81,17 +81,15 @@ public KakaoLoginResponseDto processKakaoCallback(String code) {
log.info("Jwt Access Token : {}", jwtRefreshToken);

// 5. Refresh Token 저장
// authRepository.saveRefreshToken(
// user.getId(),
// jwtRefreshToken,
// jwtTokenProvider.getRefreshTokenValidity()
// );
authRepository.saveRefreshToken(
user.getId(),
jwtRefreshToken,
jwtTokenProvider.getRefreshTokenValidity()
);

return KakaoLoginResponseDto.builder()
.accountId(1L) // Mock 데이터
.accessToken(jwtAccessToken) // 반환해주는 jwtAccessToken
.refreshToken(jwtRefreshToken) // 반환해주는 jwtRefreshToken
.isNewUser(false)
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
@Component
@RequiredArgsConstructor
public class JwtTokenProvider {
@Value("${jwt.secret}")
@Value("${spring.jwt.secret}")
private String secretKey;

private final long ACCESS_TOKEN_VALIDITY = 30 * 60 * 1000L; // 30분
Expand All @@ -39,7 +39,8 @@ public void validateToken(String token) {
Jwts.parserBuilder()
.setSigningKey(secretKey.getBytes())
.build()
.parseClaimsJws(token);
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
throw new RuntimeException("Invalid token", e);
}
Expand All @@ -62,12 +63,13 @@ public long getRefreshTokenValidity() {

public String createAccessToken(Long userId) {
Claims claims = Jwts.claims().setSubject(userId.toString());
claims.put("userid", userId);
claims.put("userId", userId); // role 없이 userId만 추가
return buildToken(claims, ACCESS_TOKEN_VALIDITY);
}

public String createRefreshToken(Long userId) {
Claims claims = Jwts.claims().setSubject(userId.toString());
claims.put("userId", userId); // userId만 추가 (role 불필요)
return buildToken(claims, REFRESH_TOKEN_VALIDITY);
}

Expand Down Expand Up @@ -97,12 +99,11 @@ public Claims getClaimsFromToken(String token) {
// 클레임에서 Authentication 객체 생성
public Authentication getAuthenticationFromClaims(Claims claims) {
Long userId = claims.get("userId", Long.class);
String role = claims.get("role", String.class);

return new UsernamePasswordAuthenticationToken(
userId,
null,
Collections.singletonList(new SimpleGrantedAuthority(role))
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
);
}
}
Loading

0 comments on commit 7db04b7

Please sign in to comment.