Mmcp.market

springboot-security skill

by affaan-m·affaan-m/ECC·269k stars·MIT

Buenas prácticas de Spring Security para autenticación/autorización, validación, CSRF, secretos, cabeceras, limitación de velocidad y seguridad de dependencias en servicios Java Spring Boot.

A100/100content scan

Is the springboot-security skill safe?

Clean: nothing in its files matched our rules. We read 1 file in the folder on 2026-09-28.

No findings.

Install the springboot-security skill

A skill is a folder. Copy it into your agent's skills folder and the agent loads it when the task matches its description.

git clone --depth 1 https://github.com/affaan-m/ECC.git /tmp/ECC
mkdir -p ~/.claude/skills
cp -r /tmp/ECC/docs/es/skills/springboot-security ~/.claude/skills/springboot-security
available in every project

In the Claude apps, zip the folder and upload it from the Skills settings. The folder on GitHub

The instructions your agent would load

SKILL.md as published, without the frontmatter. Read it on GitHub

Revisión de Seguridad Spring Boot

Usar al agregar autenticación, manejar entradas, crear endpoints o trabajar con secretos.

Cuándo Activar

  • Agregar autenticación (JWT, OAuth2, basada en sesión)
  • Implementar autorización (@PreAuthorize, control de acceso basado en roles)
  • Validar entrada de usuario (Bean Validation, validadores personalizados)
  • Configurar CORS, CSRF o cabeceras de seguridad
  • Gestionar secretos (Vault, variables de entorno)
  • Agregar limitación de velocidad o protección contra fuerza bruta
  • Escanear dependencias por CVEs

Autenticación

  • Preferir JWT sin estado o tokens opacos con lista de revocación
  • Usar cookies httpOnly, Secure, SameSite=Strict para sesiones
  • Validar tokens con OncePerRequestFilter o resource server
@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);
  }
}

Autorización

  • Habilitar seguridad de métodos: @EnableMethodSecurity
  • Usar @PreAuthorize("hasRole('ADMIN')") o @PreAuthorize("@authz.canEdit(#id)")
  • Denegar por defecto; exponer solo los scopes requeridos
@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();
  }
}

Validación de Entrada

  • Usar Bean Validation con @Valid en controllers
  • Aplicar restricciones en DTOs: @NotBlank, @Email, @Size, validadores personalizados
  • Sanitizar cualquier HTML con lista blanca antes de renderizar
// MAL: Sin validación
@PostMapping("/users")
public User createUser(@RequestBody UserDto dto) {
  return userService.create(dto);
}

// BIEN: DTO validado
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));
}

Prevención de Inyección SQL

  • Usar repositorios de Spring Data o consultas parametrizadas
  • Para consultas nativas, usar bindings :param; nunca concatenar cadenas
// MAL: Concatenación de cadenas en consulta nativa
@Query(value = "SELECT * FROM users WHERE name = '" + name + "'", nativeQuery = true)

// BIEN: Consulta nativa parametrizada
@Query(value = "SELECT * FROM users WHERE name = :name", nativeQuery = true)
List<User> findByName(@Param("name") String name);

// BIEN: Consulta derivada de Spring Data (auto-parametrizada)
List<User> findByEmailAndActiveTrue(String email);

Codificación de Contraseñas

  • Siempre hashear contraseñas con BCrypt o Argon2 — nunca almacenar en texto plano
  • Usar el bean PasswordEncoder, no hashing manual
@Bean
public PasswordEncoder passwordEncoder() {
  return new BCryptPasswordEncoder(12); // factor de costo 12
}

// En el servicio
public User register(CreateUserDto dto) {
  String hashedPassword = passwordEncoder.encode(dto.password());
  return userRepository.save(new User(dto.email(), hashedPassword));
}

Protección CSRF

  • Para aplicaciones de sesión de navegador, mantener CSRF habilitado; incluir token en formularios/cabeceras
  • Para APIs puras con tokens Bearer, deshabilitar CSRF y depender de autenticación sin estado
http
  .csrf(csrf -> csrf.disable())
  .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

Gestión de Secretos

  • Sin secretos en el código fuente; cargar desde entorno o vault
  • Mantener application.yml libre de credenciales; usar marcadores de posición
  • Rotar tokens y credenciales de base de datos regularmente
# MAL: Hardcodeado en application.yml
spring:
  datasource:
    password: mySecretPassword123

# BIEN: Marcador de variable de entorno
spring:
  datasource:
    password: ${DB_PASSWORD}

# BIEN: Integración con Spring Cloud Vault
spring:
  cloud:
    vault:
      uri: https://vault.example.com
      token: ${VAULT_TOKEN}

Cabeceras de Seguridad

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)));

Configuración de CORS

  • Configurar CORS a nivel del filtro de seguridad, no por controller
  • Restringir orígenes permitidos — nunca usar * en producción
@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;
}

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

Limitación de Velocidad

  • Aplicar Bucket4j o límites a nivel de gateway en endpoints costosos
  • Registrar y alertar sobre ráfagas; retornar 429 con hints de reintento
// Usar Bucket4j para limitación de velocidad por endpoint
@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\"}");
    }
  }
}

Seguridad de Dependencias

  • Ejecutar OWASP Dependency Check / Snyk en CI
  • Mantener Spring Boot y Spring Security en versiones soportadas
  • Fallar builds ante CVEs conocidos

Logging y PII

  • Nunca registrar secretos, tokens, contraseñas ni datos PAN completos
  • Redactar campos sensibles; usar logging JSON estructurado

Subida de Archivos

  • Validar tamaño, tipo de contenido y extensión
  • Almacenar fuera del web root; escanear si es requerido

Lista de Verificación Antes del Lanzamiento

  • [ ] Tokens de autenticación validados y con expiración correcta
  • [ ] Guardias de autorización en cada ruta sensible
  • [ ] Todas las entradas validadas y sanitizadas
  • [ ] Sin SQL concatenado con cadenas
  • [ ] Postura CSRF correcta para el tipo de aplicación
  • [ ] Secretos externalizados; ninguno con commit
  • [ ] Cabeceras de seguridad configuradas
  • [ ] Limitación de velocidad en APIs
  • [ ] Dependencias escaneadas y actualizadas
  • [ ] Logs libres de datos sensibles

Recuerda: Denegar por defecto, validar entradas, privilegio mínimo y seguro por configuración primero.

More skills from affaan-m/ECC

  • AaccessibilityWCAG 2.2 レベル AA 標準を用いてインクルーシブなデジタルプロダクトを設計・実装・監査します。Web 用のセマンティック ARIA および Web・ネイティブプラットフォーム(iOS/Android)のアクセシビリティトレイトを生成するために使用します。
  • Aagent-architecture-auditエージェントおよび LLM アプリケーション向けのフルスタック診断。12 層のエージェントスタックにおけるラッパーリグレッション、メモリ汚染、ツール規律の失敗、隠れた修復ループ、レンダリング破損を監査します。重要度順の発見事項とコードファーストの修正を生成します。エージェントアプリケーション、自律ループ、または LLM を活用した機能を構築する開発者に必須です。
  • Aagent-evalカスタムタスクでコーディングエージェント(Claude Code、Aider、Codex など)をヘッドツーヘッドで比較し、合格率、コスト、時間、一貫性のメトリクスを測定します
  • Aagent-harness-constructionAI エージェントのアクション空間、ツール定義、観測フォーマットを設計・最適化して完了率を向上させます。
  • Aagent-introspection-debuggingStructured 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.
  • Aagent-introspection-debuggingキャプチャ、診断、封じ込め回復、内省レポートを使用した AI エージェント障害のための構造化された自己デバッグワークフロー。
  • Aagent-payment-x402タスクごとのバジェット、支出コントロール、ノンカストディアルウォレットを備えた x402 決済実行を AI エージェントに追加します。agentwallet-sdk を通じて Base をサポートし、OKX Payments / OKX エージェント決済プロトコルを通じて X Layer をサポートします。
  • Aagent-sortBuild an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.
  • Aagent-sort並行リポジトリ対応のレビューパスを使用して、スキル、コマンド、ルール、フック、エクストラを DAILY と LIBRARY のバケットに分類することで、特定のリポジトリ向けのエビデンスに基づいた ECC インストール計画を構築します。プロジェクトが完全なバンドルをロードする代わりに実際に必要なものに ECC をトリミングする必要がある場合に使用します。
  • Aagentic-engineeringOperate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when AI agents perform most implementation work and humans enforce quality and risk controls.
  • Aagentic-engineering評価ファースト実行、分解、コスト対応モデルルーティングを使用してエージェニックエンジニアとして動作します。
  • Aagentic-osClaude Code 上に永続的なマルチエージェントオペレーティングシステムを構築します。カーネルアーキテクチャ、スペシャリストエージェント、スラッシュコマンド、ファイルベースのメモリ、スケジュールされた自動化、外部データベースなしの状態管理をカバーします。

All agent skills → · MCP servers