A modern, production-ready Spring Boot security framework demonstrating custom authentication, role-based authorization, and intelligent cookie-to-header transformation. Built with the latest Spring Boot 3.4.1 and Java 17.
πΉ Custom Authentication Filter - Bypass traditional login forms with programmatic authentication
πΉ Role-Based Access Control - Fine-grained permissions using @PreAuthorize
annotations
πΉ Cookie-to-Header Magic - Automatically transform cookies into HTTP headers
πΉ Modern Spring Security 6.x - Lambda-based configuration with SecurityFilterChain
πΉ Production Ready - Comprehensive error handling and audit logging
πΉ Test Coverage - Full integration tests with MockMvc
- Java 17+
- Maven 3.6+
git clone https://github.com/ravikalla/spring-custom-security.git
cd spring-custom-security
mvn spring-boot:run
The application will start on http://localhost:8080
Automatically converts cookies into HTTP headers for seamless API integration.
How it works:
// When a cookie named 'customHeader' is sent
Cookie: customHeader=MySecretValue
// It becomes available as an HTTP header
X-Custom-Header: MySecretValue
Try it yourself:
- Open browser developer tools β Application β Cookies
- Add cookie:
customHeader
=Hello World
- Visit:
http://localhost:8080/checkHeader/headerLookup/customHeader
- See the magic: Response shows
Hello World
Demonstrates programmatic authentication without traditional login forms.
@Component
public class CustomAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) {
// Create user with roles programmatically
User user = createAuthenticatedUser();
Authentication auth = new CustomAuthenticationToken(user.getRoles(), user, "DemoToken");
SecurityContextHolder.getContext().setAuthentication(auth);
filterChain.doFilter(request, response);
}
}
Fine-grained access control using Spring Security's method-level security.
@RestController
public class CheckHeader {
@PreAuthorize("hasAuthority('ADMIN')")
@GetMapping("/secured/all")
public String adminOnlyEndpoint() {
return "Welcome, Admin!";
}
@PreAuthorize("hasAuthority('ADMIN1')")
@GetMapping("/secured/alternate")
public String superAdminEndpoint() {
return "Super Admin Area";
}
}
Scenario: Transform a browser cookie into an API header
# Step 1: Set a cookie in your browser
# Developer Tools β Application β Cookies β Add:
# Name: customHeader
# Value: My Amazing Value
# Step 2: Make a request
curl -b "customHeader=My Amazing Value" \
http://localhost:8080/checkHeader/headerLookup/customHeader
# Step 3: See the result
# Response: "My Amazing Value"
Scenario: Access endpoint with proper role
# This works because user has 'ADMIN' role
curl http://localhost:8080/checkHeader/secured/all
# Response: "Secured All : User Object Content : true : 1 : [email protected] : test : test : 1"
Scenario: Try accessing endpoint without proper role
# This fails because user lacks 'ADMIN1' role
curl http://localhost:8080/checkHeader/secured/alternate
# Response: 403 Forbidden - Access Denied
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β HTTP Request βββββΆβ Cookie-Header βββββΆβ Custom Auth β
β β β Transform β β Filter β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β
βΌ
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Controller ββββββ Authorization ββββββ Security β
β @PreAuthorize β β Check β β Context β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(authz -> authz
.requestMatchers("/checkHeader/**").permitAll()
.anyRequest().authenticated()
)
.addFilterBefore(new CustomAuthenticationFilter(), BasicAuthenticationFilter.class)
.build();
}
}
@Entity
public class User implements UserDetails {
private String email;
private String name;
private Set<Role> roles;
private boolean authenticated;
// UserDetails implementation...
}
Run the comprehensive test suite:
# Run all tests
mvn test
# Run specific test
mvn test -Dtest=SecurityApplicationTests#copyCookieContentToHTTPHeader
Test Coverage:
- β Cookie-to-header transformation
- β Custom authentication flow
- β Role-based authorization
- β Error handling scenarios
This project has been upgraded from legacy versions:
Component | Before | After |
---|---|---|
Spring Boot | 1.4.7 | 3.4.1 |
Java | 8 | 17 |
Servlet API | javax.servlet | jakarta.servlet |
Spring Security | 4.x | 6.x |
JUnit | 4 | 5 |
This framework is perfect for:
- Microservices Architecture - Custom authentication between services
- API Gateway Integration - Transform cookies to headers for downstream services
- Legacy System Modernization - Bridge old cookie-based auth with modern APIs
- Educational Projects - Learn Spring Security internals
- Prototype Development - Quick security setup without external auth providers
Class | Purpose |
---|---|
CustomAuthenticationFilter |
Main authentication logic |
HttpHeaderModificationConfig |
Cookie-to-header transformation |
SecurityConfiguration |
Modern Spring Security 6.x setup |
CheckHeader |
Demo controller with role-based endpoints |
CustomAuthenticationToken |
Custom authentication token implementation |
Endpoint | Method | Auth Required | Role Required | Description |
---|---|---|---|---|
/checkHeader/all |
GET | No | None | Basic endpoint |
/checkHeader/headerLookup/{key} |
GET | No | None | Cookie-to-header demo |
/checkHeader/secured/all |
GET | Yes | ADMIN | Admin-only endpoint |
/checkHeader/secured/alternate |
GET | Yes | ADMIN1 | Super-admin endpoint |
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
β Star this repo if you found it helpful!
Built with β€οΈ by ravikalla