spring-security
$
npx mdskill add partme-ai/full-stack-skills/spring-securityGuides developers through implementing Spring Security features like authentication, authorization, OAuth2, and JWT in Spring applications.
- Helps configure security for Spring Boot apps, including access rules and user authentication.
- Integrates with Spring Security libraries, JDBC, LDAP, and OAuth2 services.
- Recommends solutions based on user queries about security setup and best practices.
- Delivers guidance through code examples and step-by-step configuration instructions.
SKILL.md
.github/skills/spring-securityView on GitHub ↗
---
name: spring-security
description: "Provides comprehensive guidance for Spring Security including authentication, authorization, OAuth2, JWT, and security best practices. Use when the user asks about Spring Security, needs to implement security in Spring applications, configure authentication, or work with security features."
license: Complete terms in LICENSE.txt
---
## When to use this skill
Use this skill whenever the user wants to:
- Configure authentication and authorization in Spring Boot applications
- Set up SecurityFilterChain, UserDetailsService, and PasswordEncoder
- Implement JWT-based stateless authentication
- Integrate OAuth2 client or resource server
- Use method-level security with @PreAuthorize and @Secured
- Configure CORS, CSRF, session management, and security headers
## How to use this skill
### Workflow
1. **Add the Spring Security starter** dependency
2. **Configure SecurityFilterChain** to define URL-based access rules
3. **Implement authentication**: in-memory, JDBC, LDAP, or custom UserDetailsService
4. **Add authorization**: role-based or expression-based access control
### 1. Basic Security Configuration
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
### 2. Custom UserDetailsService
```java
@Service
public class CustomUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
public CustomUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username) {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
return new org.springframework.security.core.userdetails.User(
user.getUsername(), user.getPassword(), user.getAuthorities()
);
}
}
```
### 3. JWT Authentication Filter
```java
@Component
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 token = extractToken(request);
if (token != null && jwtService.isValid(token)) {
String username = jwtService.extractUsername(token);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
var authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authToken);
}
chain.doFilter(request, response);
}
}
```
### 4. Method-Level Security
```java
@EnableMethodSecurity
@Configuration
public class MethodSecurityConfig {}
@Service
public class AdminService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) { /* ... */ }
@PreAuthorize("#userId == authentication.principal.id")
public UserProfile getProfile(Long userId) { /* ... */ }
}
```
## Best Practices
- Always encode passwords with BCrypt or Argon2; never store plaintext passwords
- Use HTTPS in production; configure security headers (HSTS, X-Content-Type-Options)
- Apply the principle of least privilege; design roles and permissions carefully
- Protect sensitive endpoints; use CSRF protection for browser-based applications
- Configure CORS explicitly for API servers
## Resources
- Official reference: https://docs.spring.io/spring-security/reference/
- Spring Security samples: https://github.com/spring-projects/spring-security-samples
## Keywords
spring security, authentication, authorization, JWT, OAuth2, SecurityFilterChain, UserDetailsService, BCrypt, CORS, CSRF, method security, PreAuthorize, roles, permissions
More from partme-ai/full-stack-skills
- adobe-xd"Guides creation of UI/UX designs, interactive prototypes, reusable components, and design specs in Adobe XD. Use when the user asks about Adobe XD artboards, prototype links, repeat grids, component states, design tokens export, or developer handoff."
- angular"Provides comprehensive guidance for Angular framework including components, modules, services, dependency injection, routing, forms, and TypeScript integration. Use when the user asks about Angular, needs to create Angular applications, implement Angular components, or work with Angular features."
- ansible"Provides comprehensive guidance for Ansible automation including playbooks, roles, inventory, and module usage. Use when the user asks about Ansible, needs to automate IT tasks, create Ansible playbooks, or manage infrastructure with Ansible."
- ant-design-mini"Builds mini-program UIs with Ant Design Mini components for Alipay and WeChat mini-programs. Covers Button, Form, List, Modal, Tabs, NavBar, and 60+ components with theme customization and CSS variable theming. Use when the user needs to create mini-program interfaces with Ant Design Mini, configure themes, or implement mini-program-specific UI patterns."
- ant-design-mobile"Builds React mobile UIs with Ant Design Mobile (antd-mobile) components including Button, Form, List, Modal, Picker, Tabs, PullToRefresh, InfiniteScroll, and 50+ mobile-optimized components. Use when the user needs to create mobile-first React interfaces, implement mobile navigation, forms, or data display with Ant Design Mobile."
- ant-design-react"Builds enterprise React UIs with Ant Design (antd) including 60+ components (Button, Form, Table, Select, Modal, Message), design tokens, TypeScript support, and ConfigProvider theming. Use when the user needs to create React applications with Ant Design, build forms with validation, display data tables, or customize the Ant Design theme."
- ant-design-vueProvides comprehensive guidance for Ant Design Vue (AntDV) component library for Vue 3. Covers installation, usage, API reference, templates, and all component categories. Use when building enterprise-class UI with Vue 3 and Ant Design.
- api-doc-generator"Generate API documentation by scanning Controller classes, extracting endpoint URLs, HTTP methods, parameters, and response structures, then producing standardized docs from templates. Use when the user explicitly mentions generating API documentation, creating API docs, scanning interfaces, or documenting REST APIs. Do not trigger for generic documentation requests without explicit API mention."
- appium"Provides comprehensive guidance for Appium mobile testing including mobile app automation, element location, gestures, and cross-platform testing. Use when the user asks about Appium, needs to test mobile applications, automate mobile apps, or write Appium test scripts."
- ascii-ansi-colorizer"Add an ANSI color layer to existing ASCII/plain-text output (gradient/rainbow/highlights) with alignment-safe rules and a required no-color fallback. Use when the user wants to colorize terminal output, add rainbow effects to CLI text, or style ASCII art with ANSI colors."