简体   繁体   中英

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.

在此处输入图像描述

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";
    }
}

在此处输入图像描述

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

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

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM