No bean named 'springSecurityFilterChain' is defined error with javaconfig

前端 未结 3 1789
执笔经年
执笔经年 2020-12-16 19:57

I\'m having some problems adding spring security. It shows an error that says:No bean named \'springSecurityFilterChain\' is defined

public class WebInitiali         


        
相关标签:
3条回答
  • 2020-12-16 20:32

    Try registering the security filter this way

    FilterRegistration.Dynamic securityFilter = servletContext.addFilter("springSecurityFilterChain", DelegatingFilterProxy.class);
        securityFilter.addMappingForUrlPatterns(null, false, "/*");
    

    And add the @Import({WebSecurityConfig.class}) in the configuration class you declare as your rootContext in WebInitializer in your case is in App.java

    0 讨论(0)
  • 2020-12-16 20:40

    You do not actually need to add the security filter manually. You can extend AbstractSecurityWebApplicationInitializer, which will insert the filter. You do not need to add any additional code than what is in the example below:

    package com.example.spring.security.config;
    
    import org.springframework.core.annotation.Order;
    import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
    
    @Order(1)
    public class SecurityWebAppInitializer extends AbstractSecurityWebApplicationInitializer {
    
    }
    

    I typically will have my Security App Initializer with @Order(1) and the standard Web App Initializer with @Order(2).

    You also need to make sure that your component scan is setup correctly. I have had it pointing at a wrong package and I have gotten this error before.

    0 讨论(0)
  • 2020-12-16 20:46

    You can simply create a class that extends from AbstractSecurityWebApplicationInitializer and it will automatically create/initialize the security filter chain for you. No code needed:

    public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {}
    

    Also, if you're only just creating a single dispatcher servlet, you could consider simply extending your WebAppIntializer class from AbstractAnnotationConfigDispatcherServletInitializer:

    public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    
        @Override
        protected Class<?>[] getRootConfigClasses() {
            return new Class[]{WebSecurityConfig.class, App.class};
        }
    
        @Override
        protected Class<?>[] getServletConfigClasses() {
            return new Class[]{WebConfig.class};
        }
    
        @Override
        protected String[] getServletMappings() {
            return new String[]{
                "/"
            };
        }
    
    0 讨论(0)
提交回复
热议问题