Springboot Security logo

Springboot Security

CommunityPopular
affaan-m
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.

Overview

Publisheraffaan-m
RepositoryECC
Skill namespringboot-security
Stars
261.1K
Forks
39.1K
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by affaan-m on GitHub. Read the source before you install it.

Installation

Install the Springboot Security AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
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
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Springboot Security in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Springboot Security on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Springboot Security is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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
java
@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
java
@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
java
// 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
java
// 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
java
@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
java
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
yaml
# 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

java
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
java
@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
java
// 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.

Frequently asked questions

What does the Springboot Security AI skill do?

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.

Why use Springboot Security on TypingMind?

Because you install it once and use it with any model. Springboot Security is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Springboot Security in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/affaan-m/ECC/tree/main/docs/es/skills/springboot-security. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Springboot Security?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Springboot Security?

As many as you like. As long as a model supports skills, you can use Springboot Security with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Springboot Security AI skill free?

Yes. It is published on GitHub by affaan-m under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇