affaan-m/ECC

springboot-security

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.

74CollectingNetwork access
See how to use itView GitHub source
npx skills add https://github.com/affaan-m/ECC --skill "docs/es/skills/springboot-security"
Automated source guide

Source checked Jul 28, 2026·Refresh due Oct 26, 2026

Reorganized from the pinned upstream SKILL.md

Turn springboot-security's source instructions into a guide you can follow

According to the pinned SKILL.md from affaan-m/ECC: Usar al agregar autenticación, manejar entradas, crear endpoints o trabajar con secretos.

npx skills add https://github.com/affaan-m/ECC --skill "docs/es/skills/springboot-security"
Check the pinned source

Best fit

  • 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.

Bring this context

  • A concrete task that matches the documented purpose of springboot-security.
  • The files, examples, or context the task depends on.
  • Your constraints, target environment, and definition of done.

Expected outputs

  • A result that follows the pinned springboot-security instructions.
  • A concise record of assumptions, inputs used, and unresolved questions.
  • A final check against the source workflow and relevant permission signals.

Key source sections

Read springboot-security through these 5 source sections

Sections are extracted automatically from the pinned SKILL.md and link back to the source.

01

Cuándo Activar

Agregar autenticación (JWT, OAuth2, basada en sesión)

SKILL.md · 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)
02

Autenticación

Preferir JWT sin estado o tokens opacos con lista de revocación

SKILL.md · Autenticación
Preferir JWT sin estado o tokens opacos con lista de revocaciónUsar cookies httpOnly, Secure, SameSite=Strict para sesionesValidar tokens con OncePerRequestFilter o resource server
03

Autorización

Habilitar seguridad de métodos: @EnableMethodSecurity

SKILL.md · Autorización
Habilitar seguridad de métodos: @EnableMethodSecurityUsar @PreAuthorize("hasRole('ADMIN')") o @PreAuthorize("@authz.canEdit(id)")Denegar por defecto; exponer solo los scopes requeridos
04

Validación de Entrada

Usar Bean Validation con @Valid en controllers

SKILL.md · Validación de Entrada
Usar Bean Validation con @Valid en controllersAplicar restricciones en DTOs: @NotBlank, @Email, @Size, validadores personalizadosSanitizar cualquier HTML con lista blanca antes de renderizar
05

Prevención de Inyección SQL

Usar repositorios de Spring Data o consultas parametrizadas

SKILL.md · Prevención de Inyección SQL
Usar repositorios de Spring Data o consultas parametrizadasPara consultas nativas, usar bindings :param; nunca concatenar cadenas- Usar repositorios de Spring Data o consultas parametrizadas - Para consultas nativas, usar bindings :param; nunca concatenar cadenas

SkillSignal prompt templates

Provide the task, context, and acceptance criteria

These prompts were written by SkillSignal from the source structure; they are not upstream text.

Task-start prompt

Confirm source fit, inputs, and outputs before acting.

Use springboot-security to help me with: [specific task]. Context: [files, data, or background]. Constraints: [environment, scope, and prohibited actions]. Before acting, check the pinned SKILL.md and explain which sections apply, what inputs are still missing, and what you will deliver.

Source-guided execution

Make the Agent explicitly follow the key extracted sections.

Apply the pinned springboot-security source to [task]. Pay particular attention to these source sections: “Cuándo Activar”, “Autenticación”, “Autorización”, “Validación de Entrada”, “Prevención de Inyección SQL”. Preserve the important decision at each step. Mark facts not covered by the source as “needs confirmation” instead of inventing them. Then verify the result against my acceptance criteria: [criteria].

Result-review prompt

Check omissions, permissions, and source drift before delivery.

Review the current springboot-security result: (1) does it satisfy the original task; (2) were any applicable steps or limits in the pinned SKILL.md missed; (3) did it perform any unauthorized file, command, network, or data action; and (4) which conclusions remain unverified? List issues first, then fix only what the source or user authorization supports.

Output checklist

Verify each item before delivery

The task matches the purpose documented in the SKILL.md.

The source section “Cuándo Activar” has been checked.

The source section “Autenticación” has been checked.

The source section “Autorización” has been checked.

The source section “Validación de Entrada” has been checked.

Inputs, constraints, and acceptance criteria are explicit.

Unverified facts, compatibility, and outcome claims are clearly marked.

Any file, command, network, or data action has been reviewed.

Choose a different workflow

When another Skill is the better fit

FAQ

What does springboot-security do?

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

How do I start using springboot-security?

The catalog detected this source-specific install command: npx skills add https://github.com/affaan-m/ECC --skill "docs/es/skills/springboot-security". Inspect the command and pinned source before running it.

Which Agent platforms does it declare?

No dedicated Agent platform is declared in the pinned source record.

Repository stars
234,327
Repository forks
35,711
Quality
74/100
Source repository last pushed

Quality breakdown

Based on traceable docs and repository signals; stars are not treated as quality.

74/100
Documentation28/30
Specificity11/25
Maintenance20/20
Trust signals15/25
View original Skill.mdThis page is parsed directly from the repository SKILL.md without editorial rewriting. Collected: Jul 28, 2026 · about 3 min

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.

Source repo
affaan-m/ECC
Skill path
docs/es/skills/springboot-security/SKILL.md
Commit SHA
4e973d3eaf92
Repository license
MIT
Data collected