HIGH clickjackingspring bootbasic auth

Clickjacking in Spring Boot with Basic Auth

Clickjacking in Spring Boot with Basic Auth — how this specific combination creates or exposes the vulnerability

Clickjacking is a client-side UI redress attack where an attacker tricks a user into interacting with a hidden or disguised element inside an invisible or disguised iframe. When Basic Authentication is used in a Spring Boot application, embedding user-authenticated pages inside frames can expose actions to clickjacking because the browser transmits credentials automatically with each request. A logged-in user may visit a malicious site that loads the Spring Boot app in an invisible iframe and overlay interactive controls (e.g., a button that performs a state-changing POST) on top of benign UI elements. Because the user is already authenticated via Basic Auth, the request includes the Authorization header, and the server processes the action as intended by the user, not the attacker.

Spring Boot applications that serve HTML views (e.g., Thymeleaf or JSP) and rely on HTTP Basic Auth are at risk if they do not enforce frame restrictions or anti-CSRF protections. Basic Auth sends credentials with each request, so if an authenticated session is embedded, attackers can hijack actions like changing email, updating settings, or invoking state-changing endpoints. This risk is elevated when endpoints do not validate the Origin or Referer headers and when responses are served with cache headers that allow framing. Even if Spring Security’s CSRF protection is enabled, improperly configured frame options or missing X-Frame-Options headers can still leave the app exposed when Basic Auth is used, because the browser will send credentials regardless of the framing context.

To illustrate, consider a Spring Boot controller that renders a settings page and expects a POST to /settings/update-email. If this page is loaded inside an attacker-controlled iframe and the user clicks what appears to be a harmless link, the browser will include the Basic Auth credentials automatically. The server may process the request if it only checks authentication and not a valid CSRF token or a SameSite cookie attribute. This combination makes the authenticated session usable within an embedded context, enabling unauthorized commands to be executed on behalf of the user.

Basic Auth-Specific Remediation in Spring Boot — concrete code fixes

Remediation focuses on preventing the browser from rendering the authenticated pages inside frames and ensuring that state-changing requests are protected. The primary defenses are X-Frame-Options and Content-Security-Policy (frame-ancestors), alongside robust CSRF protection. Below are concrete Spring Boot examples that combine Basic Auth configuration with frame protection.

Basic Auth Configuration in Spring Boot

Define an HTTP security configuration that enforces HTTP Basic Authentication and sets appropriate headers. This example uses Spring Security’s DSL to configure in-memory users and apply security headers.

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authz -> authz
                .requestMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .httpBasic(Customizer.withDefaults())
            .csrf(csrf -> csrf
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            )
            .headers(headers -> headers
                .frameOptions().sameOrigin()
                .contentSecurityPolicy(csp -> csp
                    .policyDirectives("frame-ancestors 'self'")
                )
            );
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("alice")
            .password("password")
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}

Key points in this configuration:

  • .httpBasic(Customizer.withDefaults()) enables HTTP Basic Authentication for protected endpoints.
  • .frameOptions().sameOrigin() sets the X-Frame-Options header to SAMEORIGIN, preventing the page from being framed by external origins.
  • .contentSecurityPolicy(... frame-ancestors 'self') adds a Content-Security-Policy header that restricts framing to same-origin, providing a modern override for browsers that support CSP.
  • CSRF protection is enabled with a cookie-based token repository, which pairs well with SameSite cookie attributes for additional defense-in-depth.

Stateless Alternative with SameSite Cookies

If you prefer a stateless approach using Basic Auth without session cookies, you can still enforce SameSite cookie behavior for any session cookies your application might use (e.g., for CSRF or other state). Explicitly configure the servlet to set SameSite cookies and ensure that no sensitive actions are performed via GET requests.

@Configuration
public class CookieConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            // Additional configuration if needed
        };
    }

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                context.setCookieProcessor(new LegacyCookieProcessor() {
                    @Override
                    public void setSameSiteCookies(SameSiteCookies sameSiteCookies) {
                        super.setSameSiteCookies(SameSiteCookies.LAX);
                    }
                });
            }
        };
        return factory;
    }
}

Combine this with the security configuration above. Even with Basic Auth, ensuring that any cookies carry SameSite=Lax or SameSite=Strict reduces the risk of credentials being sent in cross-site requests. For maximum safety, avoid embedding authenticated pages in iframes entirely; use CSP frame-ancestors to enforce this at the browser level.

Frequently Asked Questions

Does enabling HTTP Basic Auth in Spring Boot automatically protect against clickjacking?
No. Basic Auth provides authentication but does not prevent a page from being embedded in an iframe. You must explicitly set X-Frame-Options or Content-Security-Policy frame-ancestors to block framing, and use CSRF protection for state-changing requests.
Can middleBrick detect clickjacking risks on endpoints using Basic Auth?
Yes. middleBrick runs security checks including Authentication, BOLA/IDOR, and Property Authorization in parallel and reports findings with severity and remediation guidance. It also supports OpenAPI/Swagger spec analysis with full $ref resolution, cross-referencing spec definitions with runtime findings to surface misconfigurations such as missing frame protections.