개발/Spring
Spring 및 Spring Boot에서 CSP 적용 방법
피터JK
2025. 2. 4. 16:30
728x90
✅ Spring Boot에서 CSP 설정
Spring Security를 사용하여 CSP를 적용할 수 있습니다.
Spring Security 설정 예제
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.stereotype.Component;
@Component
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.headers(headers -> headers
.contentSecurityPolicy(csp -> csp.policyDirectives(
"default-src 'self'; " +
"script-src 'self' 'nonce-{nonce}'; " +
"style-src 'self' 'nonce-{nonce}'; " +
"img-src 'self' https://images.example.com; " +
"font-src 'self' https://fonts.googleapis.com; " +
"object-src 'none'; " +
"frame-src 'none'"
))
);
return http.build();
}
}
✔ 설명:
- script-src, style-src에 nonce 값을 적용하여 보안성을 높임
- img-src는 현재 도메인 및 https://images.example.com에서만 로드 가능
- object-src, frame-src는 차단
728x90