agentleFS
yeochul-jeonyeochul-jeon/spring-boot-claude-skill/skills/spring-security/SKILL.md

spring-security

Skill3 starsChanged 7 months agoMITView on GitHub

Use when configuring authentication and authorization in

5 other projects use a version of this.

Adopted by

Most recently taken up by

The file

Files
SKILL.md

Spring Security

Spring Boot 인증·인가 계층의 표준 패턴. 세션 기반 vs JWT를 먼저 결정하고, SecurityFilterChain · 비밀번호 인코더 · CORS를 순서대로 확정한 뒤 spring-principles 체크리스트로 자가 검증한다.

절대 원칙

  1. 인증 방식을 가정하지 않는다. references/selection-guide.md 체크리스트로 먼저 결정하고 사용자 승인을 받는다.
  2. 비밀번호는 DelegatingPasswordEncoder 기본. 알고리즘은 BCrypt, 평문 저장 금지.
  3. CORS는 반드시 명시. WebMvcConfigurer.addCorsMappings 대신 CorsConfigurationSource Bean으로 등록한다.
  4. WebSecurityConfigurerAdapter는 사용하지 않는다. SecurityFilterChain Bean으로 구성한다 (Spring Boot 3.x 기본 방식).

워크플로우

1. 인증 방식 선택

references/selection-guide.md 체크리스트로 세션 vs JWT 추천. 프롬프트에 이미 명시된 경우("JWT 써줘", "세션으로 해줘") 인터뷰 생략. 불명확하면 분석 결과 + 추천을 제시하고 사용자 확인.

2. 의존성 추가

build.gradle.kts에 추가:

공통

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-security")
    testImplementation("org.springframework.security:spring-security-test")
}

JWT 경로 추가

dependencies {
    implementation("io.jsonwebtoken:jjwt-api:${latestVersion}")
    runtimeOnly("io.jsonwebtoken:jjwt-impl:${latestVersion}")
    runtimeOnly("io.jsonwebtoken:jjwt-jackson:${latestVersion}")
}

JJWT 버전은 Maven Central에서 최신을 확인한다. 버전을 기억에 의존해 쓰지 않는다.

세션 + 외부 저장소(선택)

dependencies {
    implementation("org.springframework.session:spring-session-data-redis")
    implementation("org.springframework.boot:spring-boot-starter-data-redis")
}

3. SecurityFilterChain 구성

references/session-auth.md 또는 references/jwt-auth.md 패턴 적용.

공통 뼈대

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .cors(cors -> cors.configurationSource(corsConfigurationSource()))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/v1/auth/**").permitAll()
                .anyRequest().authenticated()
            );

        // 세션 경로: session-auth.md 참조
        // JWT 경로: jwt-auth.md 참조
        return http.build();
    }
}

4. 비밀번호 인코더 설정

references/password-encoding.md 참조.

@Bean
public PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();  // BCrypt 기본
}

5. CORS 설정

references/cors.md 패턴 적용.

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(List.of("${app.cors.allowed-origins}"));
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    config.setAllowedHeaders(List.of("*"));
    config.setAllowCredentials(true);

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

6. 자가 검증

spring-principles/SKILL.md 체크리스트를 실행한다.

작성 후 체크리스트

  • 세션 vs JWT 선택을 사용자에게 확인했는가
  • DelegatingPasswordEncoder (BCrypt 기본) 적용, 평문 저장 없음
  • CorsConfigurationSource Bean 등록, allowedOrigins가 환경변수·설정값으로 주입
  • JWT 선택 시: SessionCreationPolicy.STATELESS, JWT 필터 addFilterBefore 등록
  • 세션 선택 시: 세션 고정 공격 방어 (sessionFixation().changeSessionId())
  • 공개 엔드포인트 (/api/v1/auth/**) permitAll() 명시
  • CSRF: JWT는 disable, 세션은 운영 요구에 따라 활성화
  • REST API면 HttpStatusEntryPoint(UNAUTHORIZED) 등록 — 미인증 접근 302→401 (session-auth.md §6)
  • spring-security-test 의존성 포함
  • spring-principles 체크리스트 전 항목 통과
  • spring-web 체크리스트 전 항목 통과 (Controller·예외 처리·Request DTO 포함)

grep 자동 검증 패턴

체크리스트 실행 전 아래 명령으로 명백한 위반을 빠르게 탐지한다. <SRC> 는 프로젝트의 src/main/java 절대 경로.

# S1: WebSecurityConfigurerAdapter 사용 금지 (0건이어야 PASS)
grep -rn "WebSecurityConfigurerAdapter" <SRC>/

# S2: 평문 저장 / NoOp 인코더 금지 (0건이어야 PASS)
grep -rn "NoOpPasswordEncoder" <SRC>/

# S3: DelegatingPasswordEncoder 사용 확인 (1건 이상이어야 PASS)
grep -rn "DelegatingPasswordEncoder\|PasswordEncoderFactories" <SRC>/   # 0건이면 BCrypt 직접 사용 → 검토 필요

# S4: 세션 고정 공격 방어 (세션 경로라면 1건 이상이어야 PASS)
grep -rn "sessionFixation\|changeSessionId" <SRC>/   # 없으면 FAIL

# S5: CorsConfigurationSource Bean 등록 확인 (1건 이상이어야 PASS)
grep -rn "CorsConfigurationSource" <SRC>/   # 없으면 FAIL

# S6: WebMvcConfigurer.addCorsMappings 사용 금지 (0건이어야 PASS)
grep -rn "addCorsMappings" <SRC>/

# S7: HttpStatusEntryPoint 등록 (REST API라면 1건 이상이어야 PASS)
grep -rn "HttpStatusEntryPoint" <SRC>/   # 없으면 302→401 미적용 확인 필요

# S8: wildcard origin + credentials 조합 금지 (0건이어야 PASS)
grep -rn 'allowedOrigins.*"\*"' <SRC>/

# W2: @RestControllerAdvice 존재 확인 (1건 이상이어야 PASS)
grep -rn "@RestControllerAdvice" <SRC>/   # 없으면 FAIL

# W_login: @RequestBody에 Map 사용 금지 (0건이어야 PASS)
grep -rn "@RequestBody.*Map" <SRC>/*/controller/

결과가 있으면 references/ 해당 파일의 Before→After 패턴을 적용한다.

references/ 목록

파일설명
selection-guide.md세션 vs JWT 의사결정 체크리스트 (진입 시 첫 참조)
session-auth.mdSpring Session, 세션 고정 공격 방어, 세션 저장소
jwt-auth.mdJWT 발급·검증 필터, Refresh Token, 키 관리
password-encoding.mdBCrypt/Argon2 선택, DelegatingPasswordEncoder
cors.mdCorsConfigurationSource, 프런트 도메인 허용 정책

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.