Backend/spring (Boot) 27

로컬에서 Secure Cookie 테스트: Https 설정

Secure Cookie가 동작하는지 테스트가 필요한데 그러기 위해서 https 설정부터하는 과정이다!!통신하는 서버 2개 다 https설정 해야한다.📌 1. OpenSSL을 이용한 인증서 및 키 생성 과정 # 1. 개인키 생성genrsa -out my_private.key 2048# 2. CSR 생성 (← 여기서 config 지정!)req -new -key my_private.key -out my_cert.csr -config "C:\Users\dddzr\Documents\Tools\openssl-0.9.8k_X64\openssl.cnf" 🔹 경로 생략 시 기본 경로에서 찾는다: Unable to load config info from c:openssl/ssl/openssl.cnf * req 명령..

[Spring, JSP] session 생성 차단

jwt 방식 로그인을 사용하기 때문에 세션을 생성하지 않도록 Spring Security 에서 아래와 같이 설정했다.근데도 JSESSIONID가 생기고 있었다. 나는 jsp를 사용하는게 문제였다!!📌 1. 목적: 완전한 무상태(Stateless) 서버 만들기Spring Security에서 SessionCreationPolicy.STATELESS를 설정JWT 기반 인증이나 토큰 기반 인증을 쓸 때는 세션이 필요 없으므로, JSESSIONID 쿠키도 없어야 정상.http .cors(Customizer.withDefaults()) .csrf(csrf -> csrf.disable()) .sessionManagement(session -> session .sessionCreation..

Spring(boot X) 정적 리소스 처리 흐름

📌 1. 필수 설정정적 리소스를 사용하려면 반드시 설정해야 할 파일✅ 1-1. web.xml 설정 (DispatcherServlet 매핑) appServlet org.springframework.web.servlet.DispatcherServlet 1 appServlet / 이 설정으로 인해 /thumb-images/** 같은 정적 요청도 DispatcherServlet을 거치게 됨 ✅ 1-2. servlet-context.xml (또는 dispatcher-servlet.xml) 설정 -->file: 접두사는 절대경로 기반을 의미classpath:는 WAR 내부 리소스를 가리킴 (자주 쓰는 /static/, /public/ 등 포함)📌 2. 환경별 경로 차이 설정환경설정 예..

Spring boot 예외 처리: @ControllerAdvice, @ExceptionHandler, ResponseStatusException

기존에 controller에서 예외 catch해서 직접 처리하는 방식을 자주 사용했었다.@GetMapping("/user/{id}")public ResponseEntity getUser(@PathVariable Long id) { try { User user = userService.findById(id); return ResponseEntity.ok(new ApiResponse("SUCCESS", "조회 성공", user)); } catch (UserNotFoundException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(new ApiResponse("FAIL..

환경 변수 관리 (@Value, @ConfigurationProperties)

🔍 1. 환경 변수란? YAML 변수, 프로퍼티 변수, 설정 변수 라고도 부른다.환경 변수는 애플리케이션 실행 시 필요한 설정 값을 의미한다.이를 통해 코드 수정 없이 환경을 변경할 수 있고, 유지보수도 쉬워진다! 📌 2. 환경 변수 설정하기Spring Boot에서는 환경 변수를 application.yml 또는 application.properties에 저장한다. ➡️ 이 값들은 @Value나 @ConfigurationProperties를 사용해서 코드에서 가져올 수 있다!   📖 YAML 사용 (application.yml)atchfile: upload: path: /upload/files  📖 Properties 사용 (application.properties)atchfile.uplo..

[error] java.lang.IllegalArgumentException: Name for argument of type [int] not specified

🚨 Name for argument of type [int] not specified, and parameter name information not available via reflection. Ensure that the compiler uses the '-parameters' flag. java.lang.IllegalArgumentException: Name for argument of type [int] not specified Ensure that the compiler uses the '-parameters' flag. This application has no explicit mapping for /error, so you are seeing this as a fallback.Wed Fe..

[error] getOutputStream() has already been called for this response

🚨 Could not write JSON: getOutputStream() has already been called for this response  🔥 오류 원인HttpServletResponse의 getOutputStream() 또는 getWriter()가 여러 번 호출되었을 때 발생하는 문제!즉, 응답을 한 번 보낸 후에 또 응답을 보내려고 할 때 발생한다.  📖 에러 코드 (수정 전) ➡️ 쿠키를 response.addCookie()로 설정한 후, ResponseEntity로 JSON 응답을 반환. ➡️ 하지만 ResponseEntity가 HTTP 응답을 설정하는 과정에서 response.getOutputStream()을 다시 호출하기 때문에 충돌이 발생. @PostMapping("/l..

[JAVA] 쿠키(Cookie) 설정 방법

쿠키 설정 방법에 대해 알아보기전에 쿠키에 대해 간단히 알아보자!!🔍 쿠키(Cookie)란? 쿠키는 웹 브라우저에 저장되는 작은 데이터 조각!!서버가 클라이언트(브라우저)에 정보를 저장하고, 이후 요청에서 다시 전송하도록 도와주는 역할➡️ 쿠키는 웹에서 사용자 상태를 유지하는 중요한 메커니즘! 🍪 🚀 특징세션 유지: 로그인 상태 유지, 장바구니 정보 저장클라이언트 저장: 브라우저에 텍스트 형태로 저장됨자동 전송: 동일한 도메인에 대한 요청마다 자동 포함🎯 쿠키 설정 시 추가할 내용✅ HttpOnly → 자바스크립트에서 접근 불가능하게 해서 보안 강화✅ Secure → HTTPS에서만 쿠키 전송 (HTTPS 환경이라면 꼭 설정!)✅ Path=/ → 모든 경로에서 쿠키 사용 가능✅ Max-Age / ..

[Spring Security] CSRF & CORS 개념 및 설정 방법

📌 1. CSRF(Cross-Site Request Forgery)란?사용자가 로그인된 상태에서 악성 사이트를 통해 원치 않는 요청을 보내도록 유도하는 공격 방식예를 들어, 사용자가 은행 웹사이트에 로그인한 상태에서 악성 스크립트가 계좌이체 요청을 보내면 공격이 성공할 수 있음 ✅ 1-1. Spring Security에서 CSRF 설정 방법🔹 CSRF 방어 활성화 (기본값)Spring Security에서는 CSRF 보호가 기본적으로 활성화됨폼 기반 로그인(formLogin())을 사용할 때 CSRF 방어가 필요함@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { return http ..

[error] conversionServicePostProcessor Bean 중복 오류

🚨 conversionServicePostProcessor Bean 중복 오류 A bean with that name has already been defined in class path resource Description: The bean 'conversionServicePostProcessor', defined in class path resource [org/springframework/security/config/annotation/web/reactive/WebFluxSecurityConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [or..