Securing Web Services
Securing Web Services
Web services without security are open doors. REST APIs typically use JWT or OAuth2. SOAP services use WS-Security. This post covers practical security implementations.
HTTPS Everywhere
Every web service should use HTTPS. Without it, tokens and data travel in plaintext. Configure TLS in Spring Boot with a certificate or use a reverse proxy like nginx.
JWT Authentication for REST
JSON Web Tokens are the standard for stateless API authentication. The client sends a token with each request, and the server validates it without storing session state.
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@PostMapping("/login")
public ResponseEntity<Map<String, String>> login(
@RequestBody LoginRequest request) {
User user = userService.authenticate(
request.getUsername(), request.getPassword());
if (user == null) {
return ResponseEntity.status(401).build();
}
String token = jwtService.generateToken(user);
return ResponseEntity.ok(Map.of("token", token));
}
}
The Security Filter
A filter intercepts every request and validates the JWT token:
@Component
public class JwtFilter extends OncePerRequestFilter {
@Autowired
private JwtService jwtService;
@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
String header = req.getHeader("Authorization");
if (header != null && header.startsWith("Bearer ")) {
String token = header.substring(7);
if (jwtService.isValid(token)) {
UserDetails user = jwtService.parseUser(token);
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken(
user, null, user.getAuthorities()));
}
}
chain.doFilter(req, res);
}
}
SOAP Security with WS-Security
SOAP uses XML-based security headers for encryption and signing. Spring-WS supports WS-Security through the wss4j library. Configure it to require signed or encrypted messages.
CORS Configuration
Configure CORS to control which domains can access your API. Never use @CrossOrigin(allowedOrigins = "*") in production.
Key Points
- Always use HTTPS to protect data in transit.
- JWT provides stateless authentication for REST APIs.
- A security filter validates tokens on every request.
- WS-Security provides encryption and signing for SOAP messages.
- Configure CORS restrictively - never allow all origins in production.