Communitygithub.com

springboot-security

Java Spring Boot 서비스에서 인증/인가, 입력 검증, CSRF, 비밀 관리, 보안 헤더, 속도 제한, 의존성 보안 등 Spring Security 모범 사례를 제공합니다. Spring Security 인증/인가, 입력 검증, CSRF, 비밀, 헤더 또는 속도 제한을 검토할 때 사용하세요.

springboot-security란 무엇인가요?

이 스킬은 Java Spring Boot 서비스에서 Spring Security를 사용할 때 따라야 할 모범 사례와 구체적인 코드 예제를 제공합니다. 인증(stateless JWT, OAuth2, 세션 기반), 권한 부여(@PreAuthorize, 역할 기반), 입력 검증(Bean Validation), CSRF 보호, 비밀 관리(환경 변수, Vault), 보안 헤더 구성, CORS, 속도 제한(Bucket4j), 의존성 보안(OWASP Dependency Check) 등 주요 보안 영역을 다룹니다. 코드 예제는 Java와 Spring Boot 컨텍스트에 맞춰져 있으며, Claude Code, Cursor, Codex와 같은 AI 에이전트가 Spring Security 설정을 검토하거나 생성할 때 참조할 수 있습니다. 각 섹션은 명확한 '좋은 예'와 '나쁜 예'를 포함하여 개발자가 실수를 피하고 안전한 코드를 작성하도록 돕습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/springboot-security

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Spring Boot 보안 검토

인증 추가, 입력 처리, 엔드포인트 생성 또는 비밀 처리 시 사용하세요.

활성화 시점

  • 인증 추가 (JWT, OAuth2, 세션 기반)
  • 권한 부여 구현 (@PreAuthorize, 역할 기반 접근)
  • 사용자 입력 검증 (Bean Validation, 사용자 정의 검증기)
  • CORS, CSRF 또는 보안 헤더 구성
  • 비밀 관리 (Vault, 환경 변수)
  • 속도 제한 또는 무차별 대입 방지 추가
  • CVE에 대한 의존성 검사

인증

  • 무상태 JWT 또는 폐기 목록이 있는 불투명 토큰 선호
  • 세션에 대해 httpOnly, Secure, SameSite=Strict 쿠키 사용
  • OncePerRequestFilter 또는 리소스 서버로 토큰 검증
@Component
public class JwtAuthFilter extends OncePerRequestFilter {
  private final JwtService jwtService;

  public JwtAuthFilter(JwtService jwtService) {
    this.jwtService = jwtService;
  }

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain chain) throws ServletException, IOException {
    String header = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (header != null && header.startsWith("Bearer ")) {
      String token = header.substring(7);
      Authentication auth = jwtService.authenticate(token);
      SecurityContextHolder.getContext().setAuthentication(auth);
    }
    chain.doFilter(request, response);
  }
}

권한 부여

  • 메서드 보안 활성화: @EnableMethodSecurity
  • @PreAuthorize("hasRole('ADMIN')") 또는 @PreAuthorize("@authz.canEdit(#id)") 사용
  • 기본적으로 거부하고 필요한 범위만 노출
@RestController
@RequestMapping("/api/admin")
public class AdminController {

  @PreAuthorize("hasRole('ADMIN')")
  @GetMapping("/users")
  public List<UserDto> listUsers() {
    return userService.findAll();
  }

  @PreAuthorize("@authz.isOwner(#id, authentication)")
  @DeleteMapping("/users/{id}")
  public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
    userService.delete(id);
    return ResponseEntity.noContent().build();
  }
}

입력 검증

  • 컨트롤러에서 @Valid와 함께 Bean Validation 사용
  • DTO에 제약 조건 적용: @NotBlank, @Email, @Size, 사용자 정의 검증기
  • 렌더링 전에 HTML을 화이트리스트로 살균
// 나쁜 예: 검증 없음
@PostMapping("/users")
public User createUser(@RequestBody UserDto dto) {
  return userService.create(dto);
}

// 좋은 예: 검증된 DTO
public record CreateUserDto(
    @NotBlank @Size(max = 100) String name,
    @NotBlank @Email String email,
    @NotNull @Min(0) @Max(150) Integer age
) {}

@PostMapping("/users")
public ResponseEntity<UserDto> createUser(@Valid @RequestBody CreateUserDto dto) {
  return ResponseEntity.status(HttpStatus.CREATED)
      .body(userService.create(dto));
}

SQL 삽입 방지

  • Spring Data 리포지토리 또는 매개변수화된 쿼리 사용
  • 네이티브 쿼리의 경우 :param 바인딩 사용; 문자열을 절대 연결하지 마십시오
// 나쁜 예: 네이티브 쿼리에서 문자열 연결
@Query(value = "SELECT * FROM users WHERE name = '" + name + "'", nativeQuery = true)

// 좋은 예: 매개변수화된 네이티브 쿼리
@Query(value = "SELECT * FROM users WHERE name = :name", nativeQuery = true)
List<User> findByName(@Param("name") String name);

// 좋은 예: Spring Data 파생 쿼리 (자동 매개변수화)
List<User> findByEmailAndActiveTrue(String email);

비밀번호 인코딩

  • 항상 BCrypt 또는 Argon2로 비밀번호 해시 — 평문으로 저장하지 마십시오
  • 수동 해싱이 아닌 PasswordEncoder 빈 사용
@Bean
public PasswordEncoder passwordEncoder() {
  return new BCryptPasswordEncoder(12); // 비용 계수 12
}

// 서비스에서
public User register(CreateUserDto dto) {
  String hashedPassword = passwordEncoder.encode(dto.password());
  return userRepository.save(new User(dto.email(), hashedPassword));
}

CSRF 보호

  • 브라우저 세션 앱의 경우 CSRF를 활성화된 상태로 유지하고, 폼/헤더에 토큰 포함
  • Bearer 토큰이 있는 순수 API의 경우 CSRF를 비활성화하고 무상태 인증에 의존
http
  .csrf(csrf -> csrf.disable())
  .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

비밀 관리

  • 소스 코드에 비밀을 저장하지 마십시오. 환경 변수 또는 Vault에서 로드
  • application.yml을 자격 증명 없이 유지하고, 자리 표시자 사용
  • 정기적으로 토큰 및 DB 자격 증명 교체
# 나쁜 예: application.yml에 하드코딩
spring:
  datasource:
    password: mySecretPassword123

# 좋은 예: 환경 변수 자리 표시자
spring:
  datasource:
    password: ${DB_PASSWORD}

# 좋은 예: Spring Cloud Vault 통합
spring:
  cloud:
    vault:
      uri: https://vault.example.com
      token: ${VAULT_TOKEN}

보안 헤더

http
  .headers(headers -> headers
    .contentSecurityPolicy(csp -> csp
      .policyDirectives("default-src 'self'"))
    .frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
    .xssProtection(Customizer.withDefaults())
    .referrerPolicy(rp -> rp.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)));

CORS 구성

  • 보안 필터 수준에서 CORS를 구성하고, 컨트롤러별로 구성하지 마십시오
  • 허용된 출처를 제한 — 프로덕션에서 *를 절대 사용하지 마십시오
@Bean
public CorsConfigurationSource corsConfigurationSource() {
  CorsConfiguration config = new CorsConfiguration();
  config.setAllowedOrigins(List.of("https://app.example.com"));
  config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
  config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
  config.setAllowCredentials(true);
  config.setMaxAge(3600L);

  UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  source.registerCorsConfiguration("/api/**", config);
  return source;
}

// SecurityFilterChain에서:
http.cors(cors -> cors.configurationSource(corsConfigurationSource()));

속도 제한

  • 비용이 많이 드는 엔드포인트에 Bucket4j 또는 게이트웨이 수준 제한 적용
  • 버스트에 대한 로그 및 경고; 재시도 힌트와 함께 429 반환
// Bucket4j를 사용한 엔드포인트별 속도 제한
@Component
public class RateLimitFilter extends OncePerRequestFilter {
  private final Map<String, Bucket> buckets = new ConcurrentHashMap<>();

  private Bucket createBucket() {
    return Bucket.builder()
        .addLimit(Bandwidth.classic(100, Refill.intervally(100, Duration.ofMinutes(1))))
        .build();
  }

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain chain) throws ServletException, IOException {
    String clientIp = request.getRemoteAddr();
    Bucket bucket = buckets.computeIfAbsent(clientIp, k -> createBucket());

    if (bucket.tryConsume(1)) {
      chain.doFilter(request, response);
    } else {
      response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
      response.getWriter().write("{\"error\": \"Rate limit exceeded\"}");
    }
  }
}

의존성 보안

  • CI에서 OWASP Dependency Check / Snyk 실행
  • Spring Boot 및 Spring Security를 지원되는 버전으로 유지
  • 알려진 CVE에서 빌드 실패

로깅 및 PII

  • 비밀, 토큰, 비밀번호 또는 전체 PAN 데이터를 절대 로깅하지 마십시오
  • 민감한 필드를 수정하고, 구조화된 JSON 로깅 사용

파일 업로드

  • 크기, 콘텐츠 유형 및 확장자 검증
  • 웹 루트 외부에 저장하고, 필요한 경우 검사

릴리스 전 체크리스트

  • 인증 토큰이 올바르게 검증되고 만료됨
  • 모든 민감한 경로에 권한 부여 가드가 있음
  • 모든 입력이 검증되고 살균됨
  • 문자열 연결 SQL 없음
  • CSRF 상태가 앱 유형에 맞게 올바름
  • 비밀이 외부화되었으며, 커밋되지 않음
  • 보안 헤더가 구성됨
  • API에 속도 제한이 있음
  • 의존성이 검사되었고 최신 상태임
  • 로그에 민감한 데이터가 없음

기억하세요: 기본적으로 거부, 입력 검증, 최소 권한, 그리고 먼저 보안 설정으로 구성하십시오.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

관련 스킬