HIGH clickjackingspring bootbearer tokens

Clickjacking in Spring Boot with Bearer Tokens

Clickjacking in Spring Boot with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Clickjacking is a client-side UI security issue where an attacker tricks a user into interacting with a hidden or disguised element inside an invisible or embedded page. In a Spring Boot application that uses Bearer Tokens for authentication—typically passed via the Authorization header—clickjacking does not directly compromise the token itself, but it can lead to unintended authenticated actions if the user is already logged in and the application relies solely on session cookies without anti-CSRF or frame-protection mechanisms.

When a user visits a malicious site while authenticated to your Spring Boot app, the attacker can embed your application’s endpoints inside an iframe and overlay invisible UI controls (e.g., buttons or forms) that cause the user to perform actions such as changing email, initiating a transaction, or disabling security settings. Because the request includes the Bearer Token in the Authorization header, the backend processes the request as legitimate, assuming the token proves identity. If the application does not validate the Origin header or use CSRF tokens for state-changing POST/PUT/DELETE requests, this creates a privileged request forgery scenario where the bearer-bound session can be abused through UI redressing.

Spring Boot applications that serve both HTML views and API endpoints are especially at risk when the same origin hosts UI and API routes, and CORS is misconfigured to be overly permissive. Even when Bearer Tokens are used, if the application sets cookies for session identifiers (e.g., for convenience features or hybrid auth), the browser will automatically include them in embedded requests, compounding the risk. Moreover, responses that include sensitive data and lack Content-Security-Policy frame-ancestors rules can be framed by external sites, enabling data exposure via visual leakage. The combination of permissive CORS, missing X-Frame-Options or Content-Security-Policy, and bearer-based authentication without additional UI integrity controls makes the attack surface broader, as the API surface intended for programmatic access can be weaponized through social engineering and UI manipulation.

Bearer Tokens-Specific Remediation in Spring Boot — concrete code fixes

Remediation focuses on preventing your endpoints from being embedded in frames and ensuring that bearer-bound requests are not exploitable via forged UI interactions. Use strict Content-Security-Policy headers to disallow framing, and enforce same-origin policies for sensitive operations. Below are concrete Spring Boot configurations and code examples.

  • Set HTTP headers to prevent framing and restrict origins:
@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable() // for pure bearer-token APIs, CSRF is typically not required
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .headers(headers -> headers
                .contentSecurityPolicy(csp -> csp
                    .policyDirectives("default-src 'self'; frame-ancestors 'none'")
                )
                .frameOptions().disable() // CSP frame-ancestors handles framing; disable legacy X-Frame-Options if not needed
            );
        return http.build();
    }
}
  • For APIs consumed by third-party clients, use a restrictive CORS configuration that does not allow wildcard origins and does not permit framing domains:
@Configuration
public class CorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                    .allowedOrigins("https://trusted-frontend.example.com")
                    .allowedMethods("GET", "POST", "PUT", "DELETE")
                    .allowedHeaders("Authorization", "Content-Type")
                    .exposedHeaders("X-Request-ID")
                    .maxAge(3600)
                    .allowCredentials(false); // do not allow credentials on wildcard or cross-origin embeds
            }
        };
    }
}
  • When building a hybrid UI+API app and you must allow select embedding, explicitly allow only trusted ancestors and enforce Origin checks on sensitive endpoints:
@Component
public class OriginValidationFilter extends OncePerRequestFilter {

    private static final Set ALLOWED_ORIGINS = Set.of(
        "https://app.example.com",
        "https://admin.example.com"
    );

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

        String origin = request.getHeader("Origin");
        if (origin != null && !ALLOWED_ORIGINS.contains(origin)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid Origin");
            return;
        }
        // Ensure bearer token is present and well-formed for protected routes
        String auth = request.getHeader("Authorization");
        if (auth != null && auth.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing or invalid Authorization header");
        }
    }
}
  • Register the filter for sensitive paths in your SecurityConfig:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, OriginValidationFilter originValidationFilter) throws Exception {
    http.addFilterBefore(originValidationFilter, UsernamePasswordAuthenticationFilter.class);
    // other security configurations...
    return http.build();
}

These measures ensure that even if a user is tricked via clickjacking, the browser will block framing of sensitive responses, and the backend will reject requests that do not meet strict origin and authorization criteria. Remember that middleBrick scans can surface missing frame protections and overly permissive CORS as findings; the Dashboard can track these headers over time, and the CLI enables you to integrate checks into scripts, while the GitHub Action can add API security checks to your CI/CD pipeline and fail builds if risk scores drop below your chosen threshold.

Frequently Asked Questions

Does using Bearer Tokens alone prevent clickjacking?
No. Bearer Tokens authenticate requests but do not prevent a page from being embedded in an iframe. You must use frame-protection headers (Content-Security-Policy frame-ancestors or X-Frame-Options) and avoid relying on tokens alone to stop clickjacking.
Should I disable cookies entirely when using Bearer Tokens in Spring Boot?
Not necessarily. If your app serves UI and API from the same origin and you rely on cookies for any feature, keep them but ensure CSRF protections or strict CORS and framing rules. For pure bearer-token APIs, ensure cookies are not created for authenticated endpoints and configure CORS to disallow credentials.