springboot-security
Skill1 starsChanged 8 months agoMITView on GitHub
Spring Security best practices for authn/authz, validation, CSRF, secrets, headers, rate limiting, and dependency security in Java Spring Boot services.
We split this skill into the rules it gives an agent
13 rules. 8 are common, 0 are distinctive, and 5 are very specific to this project.
8
Common
Most of the 11 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Common: line 9
Use when adding auth, handling input, creating endpoints, or dealing with secrets.
- Common: line 23
Prefer stateless JWT or opaque tokens with revocation list
- Very specific: line 24
Use httpOnly, Secure, SameSite=Strict cookies for sessions
- Very specific: line 53
Use @PreAuthorize("hasRole('ADMIN')") or @PreAuthorize("@authz.canEdit(#id)")
- Very specific: line 78
Use Bean Validation with @Valid on controllers
- Common: line 105
Use Spring Data repositories or parameterized queries
- Common: line 122
Always hash passwords with BCrypt or Argon2 — never store plaintext
- Very specific: line 123
Use PasswordEncoder bean, not manual hashing
- Common: line 151
No secrets in source; load from env or vault
- Very specific: line 152
Keep application.yml free of credentials.
- Common: line 245
Run OWASP Dependency Check / Snyk in CI
- Common: line 246
Keep Spring Boot and Spring Security on supported versions
- Common: line 251
Never log secrets, tokens, passwords, or full PAN data
“Common” is measured: kept by at least 6 in 10 of the 11 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Spring Boot Security Review
Use when adding auth, handling input, creating endpoints, or dealing with secrets.
When to Activate
- Adding authentication (JWT, OAuth2, session-based)
- Implementing authorization (@PreAuthorize, role-based access)
- Validating user input (Bean Validation, custom validators)
- Configuring CORS, CSRF, or security headers
- Managing secrets (Vault, environment variables)
- Adding rate limiting or brute-force protection
- Scanning dependencies for CVEs
Authentication
- Prefer stateless JWT or opaque tokens with revocation list
- Use
httpOnly,Secure,SameSite=Strictcookies for sessions - Validate tokens with
OncePerRequestFilteror 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);
}
}Authorization
- Enable method security:
@EnableMethodSecurity - Use
@PreAuthorize("hasRole('ADMIN')")or@PreAuthorize("@authz.canEdit(#id)") - Deny by default; expose only required scopes
@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();
}
}Input Validation
- Use Bean Validation with
@Validon controllers - Apply constraints on DTOs:
@NotBlank,@Email,@Size, custom validators - Sanitize any HTML with a whitelist before rendering
// BAD: No validation
@PostMapping("/users")
public User createUser(@RequestBody UserDto dto) {
return userService.create(dto);
}
// GOOD: Validated 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 Injection Prevention
- Use Spring Data repositories or parameterized queries
- For native queries, use
:parambindings; never concatenate strings
// BAD: String concatenation in native query
@Query(value = "SELECT * FROM users WHERE name = '" + name + "'", nativeQuery = true)
// GOOD: Parameterized native query
@Query(value = "SELECT * FROM users WHERE name = :name", nativeQuery = true)
List<User> findByName(@Param("name") String name);
// GOOD: Spring Data derived query (auto-parameterized)
List<User> findByEmailAndActiveTrue(String email);Password Encoding
- Always hash passwords with BCrypt or Argon2 — never store plaintext
- Use
PasswordEncoderbean, not manual hashing
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12); // cost factor 12
}
// In service
public User register(CreateUserDto dto) {
String hashedPassword = passwordEncoder.encode(dto.password());
return userRepository.save(new User(dto.email(), hashedPassword));
}CSRF Protection
- For browser session apps, keep CSRF enabled; include token in forms/headers
- For pure APIs with Bearer tokens, disable CSRF and rely on stateless auth
http
.csrf(csrf -> csrf.disable())
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS));Secrets Management
- No secrets in source; load from env or vault
- Keep
application.ymlfree of credentials; use placeholders - Rotate tokens and DB credentials regularly
# BAD: Hardcoded in application.yml
spring:
datasource:
password: mySecretPassword123
# GOOD: Environment variable placeholder
spring:
datasource:
password: ${DB_PASSWORD}
# GOOD: Spring Cloud Vault integration
spring:
cloud:
vault:
uri: https://vault.example.com
token: ${VAULT_TOKEN}Security Headers
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 Configuration
- Configure CORS at the security filter level, not per-controller
- Restrict allowed origins — never use
*in production
@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;
}
// In SecurityFilterChain:
http.cors(cors -> cors.configurationSource(corsConfigurationSource()));Rate Limiting
- Apply Bucket4j or gateway-level limits on expensive endpoints
- Log and alert on bursts; return 429 with retry hints
// Using Bucket4j for per-endpoint rate limiting
@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\"}");
}
}
}Dependency Security
- Run OWASP Dependency Check / Snyk in CI
- Keep Spring Boot and Spring Security on supported versions
- Fail builds on known CVEs
Logging and PII
- Never log secrets, tokens, passwords, or full PAN data
- Redact sensitive fields; use structured JSON logging
File Uploads
- Validate size, content type, and extension
- Store outside web root; scan if required
Checklist Before Release
- Auth tokens validated and expired correctly
- Authorization guards on every sensitive path
- All inputs validated and sanitized
- No string-concatenated SQL
- CSRF posture correct for app type
- Secrets externalized; none committed
- Security headers configured
- Rate limiting on APIs
- Dependencies scanned and up to date
- Logs free of sensitive data
Remember: Deny by default, validate inputs, least privilege, and secure-by-configuration first.
Other versions19 projects use a version of this.
Word for word · 7
- loulanyue/awesome-claude-notes★ 272100% same
- junimnjw/everything-claude-code★ 1100% same
- SamuelNDCE/claude-super-skill-library★ 1100% same
- TironFox/everything-claude-code★ 1100% same
- davidanthonyn/claude-skills★ 0100% same
- MohamedEssam0-0/claude-skills★ 0100% same
- PeterYang888/claude-skills★ 0100% same
Edited · 12
- Fmarzochi/EGC★ 6199% same
- FaisalAlqarni/sp-ecc★ 992% same
- gongyijie85/dsh-ecc★ 898% same
- jdanigo/hydraia★ 899% same
- Lukasbrujula/claude-code-framework★ 492% same
- peopleforrester/claude-dotfiles★ 315% same
- ronmkr/PromptBook★ 299% same
- gabrielrovesti/ai-agent-skills★ 1100% same
- iCesofT/awesome-ai★ 188% same
- mstuder-slalom/everything-claude-code★ 192% same
2 more not listed
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
Used alongsideProjects with it also use nuxt4-patterns, quarkus-security and 7 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
loulanyueSkillnuxt4-patterns
Nuxt 4 app patterns for hydration safety, performance, route rules, lazy loading, and SSR-safe data fetching with useFetch and useAsyncData.
Also in 9 projects that use this
ronmkrSkillquarkus-security
Quarkus Security best practices for authentication, authorization, JWT/OIDC, RBAC, input validation, CSRF, secrets management, and dependency security.
Also in 6 projects that use this
TironFoxSkillagent-payment-x402
Add x402 payment execution to AI agents — per-task budgets, spending controls, and non-custodial wallets via MCP tools. Use when agents need to pay for APIs, services, or other agents.
Also in 5 projects that use this
ronmkrSkilldefi-amm-security
Security checklist for Solidity AMM contracts, liquidity pools, and swap flows. Covers reentrancy, CEI ordering, donation or inflation attacks, oracle manipulation, slippage, admin controls, and integer math.
Also in 6 projects that use this
junimnjwSkillralphinho-rfc-pipeline
RFC-driven multi-agent DAG execution pattern with quality gates, merge queues, and work unit orchestration.
Also in 9 projects that use this
loulanyueSkillsanta-method
Multi-agent adversarial verification with convergence loop. Two independent review agents must both pass before output ships.
Also in 7 projects that use this
- +1 more from ronmkr
In this repository71 other files it gives its agents.
- .claude/rules/common/agents.mdAGENTS.md
- docs/agents.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- api-designSkill
- article-writingSkill
- backend-patternsSkill
- clickhouse-ioSkill
- coding-standardsSkill
- configure-eccSkill
- content-engineSkill
- content-hash-cache-patternSkill
- continuous-learningSkill
- continuous-learning-v2Skill
- cost-aware-llm-pipelineSkill
- cpp-coding-standardsSkill
- cpp-testingSkill
- database-migrationsSkill
- deployment-patternsSkill
- django-patternsSkill
- django-securitySkill
- django-tddSkill
- django-verificationSkill
- docker-patternsSkill
- e2e-testingSkill
- eval-harnessSkill
- foundation-models-on-deviceSkill
- frontend-patternsSkill
- frontend-slidesSkill
- golang-patternsSkill
- golang-testingSkill
- investor-materialsSkill
- investor-outreachSkill
- iterative-retrievalSkill
- java-coding-standardsSkill
- jpa-patternsSkill
- liquid-glass-designSkill
- market-researchSkill
- nutrient-document-processingSkill
- postgres-patternsSkill
- project-guidelines-exampleSkill
- python-patternsSkill
- python-testingSkill
- regex-vs-llm-structured-textSkill
- search-firstSkill
- security-reviewSkill
- security-scanSkill
- seo-auditSkill
- seo-competitor-pagesSkill
- seo-contentSkill
- seo-geoSkill
- seo-hreflangSkill
- seo-imagesSkill
- seo-pageSkill
- seo-planSkill
- seo-programmaticSkill
- seo-schemaSkill
- seo-sitemapSkill
- seoSkill
- seo-technicalSkill
- skill-stocktakeSkill
- The first 60 shown.
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
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.

