Disable CSRF and set session creation policy to STATELESS in SecurityConfig to ensure no session is created; 2. Use JWT for token-based authentication by generating a signed token after login and returning it to the client; 3. Validate the JWT in a custom filter (JwtAuthFilter) that extracts the token from the Authorization header and sets authentication in the security context; 4. Secure endpoints using role-based access control via request matchers or method-level annotations like @PreAuthorize; 5. Follow best practices including using HTTPS, short-lived tokens, refresh tokens, rate limiting, and avoiding token logging to enhance security. This approach ensures secure, stateless, and scalable REST APIs in Java with Spring Security.
Securing REST APIs in Java using Spring Security is a common requirement for modern web applications. Since REST APIs are stateless by design, traditional session-based security doesn't fit well. Spring Security, however, provides flexible tools to secure REST endpoints effectively—especially when combined with token-based authentication like JWT (JSON Web Tokens).

Here’s how to properly secure REST APIs in Java using Spring Security:
1. Disable CSRF and Enable Stateless Authentication
REST APIs are typically consumed by frontend apps, mobile clients, or third-party services, not browsers relying on cookies. So, CSRF protection is unnecessary and can interfere with API calls.

In your SecurityConfig
, disable CSRF and set the session strategy to stateless:
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf().disable() // Not needed for stateless APIs .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeHttpRequests(authz -> authz .requestMatchers("/api/public/**").permitAll() .requestMatchers("/api/admin/**").hasRole("ADMIN") .anyRequest().authenticated() ) .httpBasic().disable() // Prefer token-based over Basic Auth .addFilterBefore(jwtAuthFilter(), UsernamePasswordAuthenticationFilter.class); return http.build(); } @Bean public AuthenticationManager authenticationManager( AuthenticationConfiguration authConfig) throws Exception { return authConfig.getAuthenticationManager(); } @Bean public JwtAuthFilter jwtAuthFilter() { return new JwtAuthFilter(); } }
? Key Point: Use
SessionCreationPolicy.STATELESS
so Spring doesn’t create or use HTTP sessions.
2. Use JWT for Token-Based Authentication
JWT is a compact, URL-safe way to represent claims between parties. It’s ideal for REST APIs because it carries user info and is self-contained.
Steps to Implement JWT:
- Generate Token: After successful login, generate a JWT containing user details (e.g., username, roles).
- Send Token: Return it in the response (usually in JSON body or
Authorization
header). - Validate Token: On each request, extract and validate the JWT from the
Authorization: Bearer <token>
header.
Example of a simple JwtUtil
class:
@Component public class JwtUtil { private String secret = "yourSecretKey"; // Use a strong key from environment private int expiry = 86400; // 24 hours public String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); return Jwts.builder() .setClaims(claims) .setSubject(userDetails.getUsername()) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() expiry * 1000)) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } public boolean isTokenValid(String token, String username) { return getUsernameFromToken(token).equals(username) && !isTokenExpired(token); } public String getUsernameFromToken(String token) { return getClaim(token, Claims::getSubject); } private <T> T getClaim(String token, Function<Claims, T> resolver) { Claims claims = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); return resolver.apply(claims); } private boolean isTokenExpired(String token) { return getClaim(token, Claims::getExpiration).before(new Date()); } }
?? Never hardcode the secret key in production—use environment variables or a secrets manager.
3. Custom Filter to Intercept and Validate JWT
Create a filter that runs before the main authentication chain to check for the JWT in the request header.
@Component public class JwtAuthFilter extends OncePerRequestFilter { @Autowired private UserDetailsService userDetailsService; @Autowired private JwtUtil jwtUtil; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { final String header = request.getHeader("Authorization"); String jwt = null; String username = null; if (header != null && header.startsWith("Bearer ")) { jwt = header.substring(7); try { username = jwtUtil.getUsernameFromToken(jwt); } catch (Exception e) { // Invalid token } } if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (jwtUtil.isTokenValid(jwt, userDetails.getUsername())) { UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authToken); } } chain.doFilter(request, response); } }
This filter:
- Extracts the token from the
Authorization
header. - Parses and validates it.
- Loads the user and sets the authentication in the security context.
4. Secure Endpoints with Proper Role-Based Access
Use Spring Security annotations to protect methods or endpoints:
@RestController @RequestMapping("/api/admin") @PreAuthorize("hasRole('ADMIN')") public class AdminController { @GetMapping("/users") public List<User> getAllUsers() { // Only accessible to ADMIN } }
Enable method-level security:
@Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) public class MethodSecurityConfig { // No additional config needed }
5. Additional Security Best Practices
- ? Use HTTPS: Always serve APIs over HTTPS to protect tokens in transit.
- ? Set short token expiration: Reduce the window of exposure if a token is stolen.
- ? Refresh tokens: Use a refresh token mechanism to reissue access tokens without re-login.
- ? Rate limiting: Prevent brute-force attacks using tools like
Bucket4j
orSpring Cloud Gateway
. - ? Avoid logging tokens: Ensure tokens aren’t accidentally logged in server logs.
Summary
To secure REST APIs in Java with Spring Security:
- Disable CSRF and use stateless sessions.
- Use JWT for authentication instead of sessions.
- Validate tokens via a custom filter.
- Enforce access control with method or path-level security.
- Follow security best practices (HTTPS, short-lived tokens, etc.).
With this setup, your REST APIs will be both secure and scalable—perfect for SPAs, mobile apps, or microservices.
Basically, it's not complex once you get the flow: authenticate once, get a token, and prove identity on every request without sessions.
The above is the detailed content of Securing REST APIs in Java using Spring Security. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Maven is a standard tool for Java project management and construction. The answer lies in the fact that it uses pom.xml to standardize project structure, dependency management, construction lifecycle automation and plug-in extensions; 1. Use pom.xml to define groupId, artifactId, version and dependencies; 2. Master core commands such as mvnclean, compile, test, package, install and deploy; 3. Use dependencyManagement and exclusions to manage dependency versions and conflicts; 4. Organize large applications through multi-module project structure and are managed uniformly by the parent POM; 5.

SetupaMaven/GradleprojectwithJAX-RSdependencieslikeJersey;2.CreateaRESTresourceusingannotationssuchas@Pathand@GET;3.ConfiguretheapplicationviaApplicationsubclassorweb.xml;4.AddJacksonforJSONbindingbyincludingjersey-media-json-jackson;5.DeploytoaJakar

@property decorator is used to convert methods into properties to implement the reading, setting and deletion control of properties. 1. Basic usage: define read-only attributes through @property, such as area calculated based on radius and accessed directly; 2. Advanced usage: use @name.setter and @name.deleter to implement attribute assignment verification and deletion operations; 3. Practical application: perform data verification in setters, such as BankAccount to ensure that the balance is not negative; 4. Naming specification: internal variables are prefixed, property method names are consistent with attributes, and unified access control is used to improve code security and maintainability.

First, use JavaScript to obtain the user system preferences and locally stored theme settings, and initialize the page theme; 1. The HTML structure contains a button to trigger topic switching; 2. CSS uses: root to define bright theme variables, .dark-mode class defines dark theme variables, and applies these variables through var(); 3. JavaScript detects prefers-color-scheme and reads localStorage to determine the initial theme; 4. Switch the dark-mode class on the html element when clicking the button, and saves the current state to localStorage; 5. All color changes are accompanied by 0.3 seconds transition animation to enhance the user

Yes, a common CSS drop-down menu can be implemented through pure HTML and CSS without JavaScript. 1. Use nested ul and li to build a menu structure; 2. Use the:hover pseudo-class to control the display and hiding of pull-down content; 3. Set position:relative for parent li, and the submenu is positioned using position:absolute; 4. The submenu defaults to display:none, which becomes display:block when hovered; 5. Multi-level pull-down can be achieved through nesting, combined with transition, and add fade-in animations, and adapted to mobile terminals with media queries. The entire solution is simple and does not require JavaScript support, which is suitable for large

Understand the core components of blockchain, including blocks, hashs, chain structures, consensus mechanisms and immutability; 2. Create a Block class that contains data, timestamps, previous hash and Nonce, and implement SHA-256 hash calculation and proof of work mining; 3. Build a Blockchain class to manage block lists, initialize the Genesis block, add new blocks and verify the integrity of the chain; 4. Write the main test blockchain, add transaction data blocks in turn and output chain status; 5. Optional enhancement functions include transaction support, P2P network, digital signature, RESTAPI and data persistence; 6. You can use Java blockchain libraries such as HyperledgerFabric, Web3J or Corda for production-level opening

To generate hash values using Java, it can be implemented through the MessageDigest class. 1. Get an instance of the specified algorithm, such as MD5 or SHA-256; 2. Call the .update() method to pass in the data to be encrypted; 3. Call the .digest() method to obtain a hash byte array; 4. Convert the byte array into a hexadecimal string for reading; for inputs such as large files, read in chunks and call .update() multiple times; it is recommended to use SHA-256 instead of MD5 or SHA-1 to ensure security.

Use datetime.strptime() to convert date strings into datetime object. 1. Basic usage: parse "2023-10-05" as datetime object through "%Y-%m-%d"; 2. Supports multiple formats such as "%m/%d/%Y" to parse American dates, "%d/%m/%Y" to parse British dates, "%b%d,%Y%I:%M%p" to parse time with AM/PM; 3. Use dateutil.parser.parse() to automatically infer unknown formats; 4. Use .d
