diff --git a/HealthMer/src/main/java/com/minijean/healthmer/config/SecurityConfig.java b/HealthMer/src/main/java/com/minijean/healthmer/config/SecurityConfig.java index 504eba9..d81f8e1 100644 --- a/HealthMer/src/main/java/com/minijean/healthmer/config/SecurityConfig.java +++ b/HealthMer/src/main/java/com/minijean/healthmer/config/SecurityConfig.java @@ -11,21 +11,21 @@ @Configuration @EnableWebSecurity public class SecurityConfig { - - @Bean - PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - - // 인증 비활성화 + + @Bean + PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + // 인증 비활성화 @Bean - SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { - http - .csrf(csrf -> csrf.disable()) // CSRF 비활성화 - .authorizeHttpRequests(auth -> auth - .anyRequest().permitAll() // 모든 요청을 인증 없이 허용 - ); + SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http + .cors() // CORS 설정을 Spring Security에서도 허용 + .and() + .csrf(csrf -> csrf.disable()) // CSRF 비활성화 + .authorizeHttpRequests(auth -> auth.anyRequest().permitAll()); - return http.build(); - } + return http.build(); + } } diff --git a/HealthMer/src/main/java/com/minijean/healthmer/config/WebConfig.java b/HealthMer/src/main/java/com/minijean/healthmer/config/WebConfig.java index 64f9158..99613b4 100644 --- a/HealthMer/src/main/java/com/minijean/healthmer/config/WebConfig.java +++ b/HealthMer/src/main/java/com/minijean/healthmer/config/WebConfig.java @@ -1,8 +1,9 @@ package com.minijean.healthmer.config; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @@ -20,4 +21,19 @@ public void addInterceptors(InterceptorRegistry registry) { .addPathPatterns("/api/v1/**") // 토큰 검증이 필요한 경로 설정 .excludePathPatterns("/api/v1/auth/login/email", "/api/v1/auth/register/email"); // 인증 관련 경로 제외 (로그인, 회원가입 등) } + + // CORS 전역 설정 + @Bean + WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/api/**") + .allowedOrigins("http://localhost:5173") + .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") + .allowedHeaders("*") + .allowCredentials(true); + } + }; + } } \ No newline at end of file diff --git a/HealthMer/src/main/java/com/minijean/healthmer/controller/AuthController.java b/HealthMer/src/main/java/com/minijean/healthmer/controller/AuthController.java index 4285e80..7ec4f7e 100644 --- a/HealthMer/src/main/java/com/minijean/healthmer/controller/AuthController.java +++ b/HealthMer/src/main/java/com/minijean/healthmer/controller/AuthController.java @@ -13,16 +13,13 @@ @RestController @RequestMapping("/api/v1/auth") -@CrossOrigin("http://localhost:5173") public class AuthController { // @Autowired private final AuthService authService; - private final JwtUtil jwtUtil; - public AuthController(AuthService authService, JwtUtil jwtUtil) { + public AuthController(AuthService authService) { this.authService = authService; - this.jwtUtil = jwtUtil; } @PostMapping("/register/email") @@ -47,24 +44,6 @@ public ResponseEntity register(@RequestBody User user) { } // 로그인 -// @PostMapping("/login/email") -// public ResponseEntity login(@RequestBody User user) { -// HttpStatus status = null; -// Map result = new HashMap<>(); -// String loginUserToken = authService.login(user); -// -// if (loginUserToken != null) { -// result.put("message", "Login Successfully"); -// result.put("access-token", jwtUtil.createToken(loginUserToken)); -// status = HttpStatus.ACCEPTED; -// } else { -// status = HttpStatus.INTERNAL_SERVER_ERROR; -// } -// -// ResponseEntity entity = new ResponseEntity<>(result, status); -// return new ResponseEntity<>(result, status); -// } - @PostMapping("/login/email") public ResponseEntity login(@RequestBody User user) { HttpStatus status; @@ -72,14 +51,13 @@ public ResponseEntity login(@RequestBody User user) { String loginUserToken = authService.login(user); if (loginUserToken != null) { // 로그인 성공 시 메시지와 토큰 추가 - String token = jwtUtil.createToken(loginUserToken); result.put("message", "Login Successfully"); - result.put("access-token", token); - status = HttpStatus.ACCEPTED; + result.put("access_token", loginUserToken); + status = HttpStatus.ACCEPTED; // ResponseEntity에 헤더 추가 return ResponseEntity.status(status) - .header("Authorization", "Bearer " + token) + .header("Authorization", "Bearer " + loginUserToken) .body(result); } else { // 로그인 실패 시 처리 diff --git a/HealthMer/src/main/java/com/minijean/healthmer/controller/TimerController.java b/HealthMer/src/main/java/com/minijean/healthmer/controller/TimerController.java index b71e2f6..f057723 100644 --- a/HealthMer/src/main/java/com/minijean/healthmer/controller/TimerController.java +++ b/HealthMer/src/main/java/com/minijean/healthmer/controller/TimerController.java @@ -25,7 +25,6 @@ @RestController @RequestMapping("/api/v1/timer") -@CrossOrigin("http://localhost:5173") public class TimerController { private final TimerService timerService; diff --git a/HealthMer/src/main/java/com/minijean/healthmer/controller/UserController.java b/HealthMer/src/main/java/com/minijean/healthmer/controller/UserController.java index 02d24a4..de9e5fa 100644 --- a/HealthMer/src/main/java/com/minijean/healthmer/controller/UserController.java +++ b/HealthMer/src/main/java/com/minijean/healthmer/controller/UserController.java @@ -6,6 +6,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/HealthMer/src/main/java/com/minijean/healthmer/interceptor/BearerTokenInterceptor.java b/HealthMer/src/main/java/com/minijean/healthmer/interceptor/BearerTokenInterceptor.java index 36823d8..24b6d54 100644 --- a/HealthMer/src/main/java/com/minijean/healthmer/interceptor/BearerTokenInterceptor.java +++ b/HealthMer/src/main/java/com/minijean/healthmer/interceptor/BearerTokenInterceptor.java @@ -23,7 +23,6 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons // Bearer 이후의 토큰 추출 String token = authorizationHeader.substring(7); - // 토큰 유효성 검사 (예: JWT 검증) if (!isValidToken(token)) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); diff --git a/HealthMer/src/main/java/com/minijean/healthmer/model/service/AuthServiceImpl.java b/HealthMer/src/main/java/com/minijean/healthmer/model/service/AuthServiceImpl.java index 5da992a..1448eaf 100644 --- a/HealthMer/src/main/java/com/minijean/healthmer/model/service/AuthServiceImpl.java +++ b/HealthMer/src/main/java/com/minijean/healthmer/model/service/AuthServiceImpl.java @@ -12,8 +12,8 @@ public class AuthServiceImpl implements AuthService { private final AuthDao authDao; - private final JwtUtil jwtUtil; - private final PasswordEncoder passwordEncoder; + private final JwtUtil jwtUtil; + private final PasswordEncoder passwordEncoder; public AuthServiceImpl(AuthDao authDao, JwtUtil jwtUtil, PasswordEncoder passwordEncoder) { this.authDao = authDao; @@ -26,16 +26,16 @@ public AuthServiceImpl(AuthDao authDao, JwtUtil jwtUtil, PasswordEncoder passwor public boolean register(User user) { User findUserForEmail = authDao.findByEmail(user.getEmail()); User findUserForNickname = authDao.findByNickname(user.getNickname()); - + if (findUserForEmail == null && findUserForNickname == null) { user.setUserTypeId((byte) 2); user.setSignUpRouteId((byte) 5); user.setPassword(passwordEncoder.encode(user.getPassword())); - + authDao.registUser(user); - + User data = authDao.findByEmail(user.getEmail()); - + if (data == null) { return false; } else { @@ -44,14 +44,17 @@ public boolean register(User user) { } return false; } - + @Override public String login(User user) { - User findedUser = authDao.findByEmail(user.getEmail()); - if (user == null || !passwordEncoder.matches(user.getPassword(), findedUser.getPassword())) { - throw new IllegalArgumentException("Invalid email or password"); - } - return jwtUtil.createToken(findedUser.getEmail()); + User findedUser = authDao.findByEmail(user.getEmail()); + if (user == null || !passwordEncoder.matches(user.getPassword(), findedUser.getPassword())) { + throw new IllegalArgumentException("Invalid email or password"); + } + + String token = jwtUtil.createTokenBy(findedUser); + + return token; } @Override diff --git a/HealthMer/src/main/java/com/minijean/healthmer/util/JwtUtil.java b/HealthMer/src/main/java/com/minijean/healthmer/util/JwtUtil.java index 2fff3cb..e5f0b10 100644 --- a/HealthMer/src/main/java/com/minijean/healthmer/util/JwtUtil.java +++ b/HealthMer/src/main/java/com/minijean/healthmer/util/JwtUtil.java @@ -7,6 +7,8 @@ import org.springframework.stereotype.Component; +import com.minijean.healthmer.model.dto.User; + import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; @@ -16,15 +18,27 @@ public class JwtUtil { private String key = "SSAFY_NonMajor_JavaTrack_SecretKey"; private SecretKey secretKey = Keys.hmacShaKeyFor(key.getBytes(StandardCharsets.UTF_8)); - - public String createToken(String name) { - Date exp = new Date(System.currentTimeMillis()+ 1000*60*60*6); - return Jwts.builder().header().add("typ", "JWT").and() - .claim("name", name).expiration(exp) - .signWith(secretKey).compact(); + + public String createTokenBy(User user) { + Date exp = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 6); + return Jwts.builder().header().add("typ", "JWT").and().claim("id", user.getId()).claim("email", user.getEmail()) + .expiration(exp).signWith(secretKey).compact(); } - - public Jws vaildate(String token){ + +// public String createLoginToken(String name) { +// Date exp = new Date(System.currentTimeMillis()+ 1000*60*60*6); +// return Jwts.builder().header().add("typ", "JWT").and() +// .claim("name", name).expiration(exp) +// .signWith(secretKey).compact(); +// } + + public Jws validate(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token); } + + public String extractUserId(String token) { + // getBody() 메서드가 deprecated된 경우 대안은 라이브러리의 최신 문서를 참조하여 새로운 API로 업데이트된 방식에 맞게 코드를 작성하는 것입니다. 하지만, 현재의 최신 JJWT 라이브러리에서는 위의 방식이 유효하고 권장되는 패턴입니다. + Claims claims = validate(token).getBody(); // 클레임을 추출하는 권장되는 방법 사용 + return claims.get("id", String.class); // "id" 클레임에서 사용자 ID 추출 + } } \ No newline at end of file