Search code examples
javaspringwebspring-securityx-frame-options

Spring Security Anotation @EnableWebSecurity does not works in Spring MVC project


I have to enable X-Frame-Options: SAMEORIGIN in my spring MVC project, to return this param in to http response header. Project is deployed on Apache Tomcat 9.

here is my web security configuration

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().sameOrigin();
    }
}

This is how I initialize dispatcher servlet

public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{AppConfig.class, WebSecurityConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

In spring security documentation (https://docs.spring.io/spring-security/site/docs/5.3.1.RELEASE/reference/html5/#headers) it's mentioned that

Spring Security provides a default set of security related HTTP response headers to provide secure defaults.

But, I can't see any security header in Response Header, it seems that spring security is not enabled in my project.

enter image description here

If I add header option manually in to @Controller class method it works

@Controller
public class WController {
    @GetMapping("/hello")
    public String sayHello(HttpServletResponse response, Model model) {
        response.setHeader("X-Frame-Options", "SAMEORIGIN");
        return "htmlPageTemplate";
    }
}

enter image description here

Please check, What I made wrong. How to fix and enable web security properly?


Solution

  • I missed filter, just added new class to extend AbstractSecurityWebApplicationInitializer, and it fixed the problem.

    public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
    
    }