springboot-security
Skill3 starsChanged 8 months agoMITView on GitHub
Spring Security 6.x best practices. Covers SecurityFilterChain, JWT auth, OAuth2, CORS, CSRF, method-level security, password encoding, and rate limiting for Spring Boot 3.x applications.
- Reads credentials
17 other projects use a version of this, 14 of them edited.
Adopted by
Most recently taken up by
- templetongroup/radiantedited, first seen Sep 17, 2026
- jdanigo/hydraiaedited, first seen Sep 12, 2026
- SamuelNDCE/claude-super-skill-libraryedited, first seen Aug 1, 2026
- JunMystery/Agent-Guidance-Pythonedited, first seen Jul 21, 2026
- Lukasbrujula/claude-code-frameworktheir own version, first seen Jul 6, 2026
- romaintoso78/claude-skillsedited, first seen Jun 25, 2026
Used with
Projects with it also use kotlin-testing, nuxt4-patterns and 10 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.
tpavanipradeepSkillkotlin-testing
Kotlin testing patterns with Kotest, MockK, coroutine testing, property-based testing, and Kover coverage. Follows TDD methodology with idiomatic Kotlin practices.
Also in 6 projects that use this
mryeastcodeSkillnuxt4-patterns
Nuxt 4 app patterns for hydration safety, performance, route rules, lazy loading, and SSR-safe data fetching with useFetch and useAsyncData.
Also in 5 projects that use this
InfopibeSkillralphinho-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
saxon-ySkillconfigure-ecc
Interactive installer for Everything Claude Code — guides users through selecting and installing skills and rules to user-level or project-level directories, verifies paths, and optionally optimizes installed files.
Also in 11 projects that use this
InfopibeSkillcontent-hash-cache-pattern
Cache expensive file processing results using SHA-256 content hashes — path-independent, auto-invalidating, with service layer separation.
Also in 10 projects that use this
mryeastcodeSkillsanta-method
Multi-agent adversarial verification with convergence loop. Two independent review agents must both pass before output ships.
Also in 6 projects that use this
- +3 more from Infopibe
Other versions17 projects use a version of this.
Word for word · 0
None found.
Edited · 14
- xu-xiang/everything-claude-code-zh★ 2k15% same
- loulanyue/awesome-claude-notes★ 27213% same
- tpavanipradeep/everything-claude-code★ 13413% same
- templetongroup/radiant★ 11313% same
- codelably/harmony-claude-code★ 4310% same
- Infopibe/everything-claude-code★ 813% same
- jdanigo/hydraia★ 813% same
- JunMystery/Agent-Guidance-Python★ 213% same
- ashutoshrathi0909-oss/everything-claude-code★ 113% same
- iCesofT/awesome-ai★ 111% same
4 more not listed
Wrote their own version · 3
- Jamkris/everything-gemini-code★ 87same name
- FaisalAlqarni/sp-ecc★ 9same name
- Lukasbrujula/claude-code-framework★ 4same name
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.
In this repository72 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- llms.txtllms.txt
- api-designerSkill
- backend-patternsSkill
- code-reviewerSkill
- debugging-assistantSkill
- golang-testingSkill
- project-guidelines-exampleSkill
- python-testingSkill
- refactoring-guideSkill
- spec-driven-developmentSkill
- tdd-workflowSkill
- verification-loopSkill
- update-docsSkill
- api-docsSkill
- changelog-writerSkill
- readme-generatorSkill
- django-patternsSkill
- django-securitySkill
- django-tddSkill
- django-verificationSkill
- fastapi-patternsSkill
- nextjs-patternsSkill
- react-patternsSkill
- springboot-patternsSkill
- springboot-tddSkill
- branch-strategySkill
- changelogSkill
- commit-helperSkill
- pr-creatorSkill
- prSkill
- evolveSkill
- instinct-exportSkill
- instinct-importSkill
- instinct-statusSkill
- cleanupSkill
- lint-fixSkill
- refactor-cleanSkill
- update-depsSkill
- continuous-learningSkill
- continuous-learning-v2Skill
- eval-harnessSkill
- iterative-retrievalSkill
- strategic-compactSkill
- golang-patternsSkill
- python-patternsSkill
- rust-patternsSkill
- typescript-patternsSkill
- accessibility-checkerSkill
- build-fixSkill
- code-reviewSkill
- e2eSkill
- performance-reviewerSkill
- security-auditorSkill
- security-reviewSkill
- test-coverageSkill
- checkpointSkill
- deploySkill
- evalSkill
- The first 60 shown.
The file
Files
Spring Boot Security Patterns
Security configuration for Spring Boot 3.x with Spring Security 6.x.
SecurityFilterChain Configuration
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final JwtAuthFilter jwtAuthFilter;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable()) // Disable for stateless API
.cors(cors -> cors.configurationSource(corsConfig()))
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/actuator/health").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
private CorsConfigurationSource corsConfig() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://example.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
config.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", config);
return source;
}
}JWT Authentication Filter
@Component
@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {
private final JwtService jwtService;
private final UserDetailsService userDetailsService;
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
chain.doFilter(request, response);
return;
}
String token = header.substring(7);
String username = jwtService.extractUsername(token);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (jwtService.isValid(token, userDetails)) {
UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(auth);
}
}
chain.doFilter(request, response);
}
}JWT Service
@Service
public class JwtService {
@Value("${jwt.secret}")
private String secretKey;
@Value("${jwt.expiration:3600000}") // 1 hour default
private long expiration;
public String generateToken(UserDetails userDetails) {
return Jwts.builder()
.subject(userDetails.getUsername())
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + expiration))
.signWith(getSigningKey())
.compact();
}
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}
public boolean isValid(String token, UserDetails userDetails) {
String username = extractUsername(token);
return username.equals(userDetails.getUsername()) && !isExpired(token);
}
private boolean isExpired(String token) {
return extractClaim(token, Claims::getExpiration).before(new Date());
}
private <T> T extractClaim(String token, Function<Claims, T> resolver) {
Claims claims = Jwts.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(token)
.getPayload();
return resolver.apply(claims);
}
private SecretKey getSigningKey() {
return Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretKey));
}
}Method-Level Security
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(UUID id) {
userRepository.deleteById(id);
}
@PreAuthorize("#userId == authentication.principal.id or hasRole('ADMIN')")
public UserResponse getUser(UUID userId) {
return userRepository.findById(userId)
.map(UserResponse::from)
.orElseThrow(() -> new ResourceNotFoundException("User", userId));
}
@PostAuthorize("returnObject.email == authentication.principal.username")
public UserResponse getCurrentUser() {
// Only return if result matches authenticated user
return findCurrentUser();
}
}Input Validation
// Request DTOs with validation constraints
public record LoginRequest(
@NotBlank @Email String email,
@NotBlank @Size(min = 8, max = 128) String password
) {}
public record RegisterRequest(
@NotBlank @Size(min = 2, max = 50) String name,
@NotBlank @Email String email,
@NotBlank @Size(min = 12, max = 128)
@Pattern(regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).*$",
message = "Must contain uppercase, lowercase, and digit")
String password
) {}Rate Limiting
// Using Bucket4j for rate limiting
@Component
@RequiredArgsConstructor
public class RateLimitFilter extends OncePerRequestFilter {
private final Map<String, Bucket> buckets = new ConcurrentHashMap<>();
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String clientIp = request.getRemoteAddr();
Bucket bucket = buckets.computeIfAbsent(clientIp, this::createBucket);
if (bucket.tryConsume(1)) {
chain.doFilter(request, response);
} else {
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.getWriter().write("{\"error\":\"Rate limit exceeded\"}");
}
}
private Bucket createBucket(String key) {
return Bucket.builder()
.addLimit(Bandwidth.classic(100, Refill.greedy(100, Duration.ofMinutes(1))))
.build();
}
}Security Headers
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.headers(headers -> headers
.contentTypeOptions(Customizer.withDefaults())
.frameOptions(frame -> frame.deny())
.httpStrictTransportSecurity(hsts -> hsts
.includeSubDomains(true)
.maxAgeInSeconds(31536000))
.contentSecurityPolicy(csp -> csp
.policyDirectives("default-src 'self'; frame-ancestors 'none'")))
// ... rest of config
.build();
}Secrets Configuration
# application.yml - reference environment variables
spring:
datasource:
url: ${DATABASE_URL}
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
jwt:
secret: ${JWT_SECRET_KEY}
expiration: ${JWT_EXPIRATION:3600000}Checklist
- SecurityFilterChain configured (not deprecated WebSecurityConfigurerAdapter)
- Stateless session management for API applications
- BCrypt password encoder with cost factor >= 12
- JWT secrets loaded from environment, never hardcoded
- Method-level security with
@PreAuthorizefor fine-grained access - CORS restricted to specific origins
- Rate limiting on authentication endpoints
- Input validation on all request DTOs
- Security headers configured (HSTS, CSP, X-Frame-Options)
- Actuator endpoints secured (health only public)
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.

