Spring Boot setup security for testing

后端 未结 2 1329
悲&欢浪女
悲&欢浪女 2020-12-16 03:45

I\'m unable to configure correctly the security in my tests. My web security configuration:

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConf         


        
相关标签:
2条回答
  • 2020-12-16 04:19

    As said in reference for Spring Security 4.0.4:

    In order to use Spring Security with Spring MVC Test it is necessary to add the Spring Security FilterChainProxy as a Filter. It is also necessary to add Spring Security’s TestSecurityContextHolderPostProcessor to support Running as a User in Spring MVC Test with Annotations. This can be done using Spring Security’s SecurityMockMvcConfigurers.springSecurity().

    Example:

    import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    @WebAppConfiguration
    public class TestControllerTest {
    
        @Autowired
        private WebApplicationContext wac;
    
        private MockMvc mockMvc;
    
        @Before
        public void setup() {
            mockMvc = MockMvcBuilders
                    .webAppContextSetup(wac)
                    .apply(springSecurity()) //will perform all of the initial setup to integrate Spring Security with Spring MVC Test
                    .build();
        }
    
    0 讨论(0)
  • 2020-12-16 04:21

    Make the following modifications to your code:

       @Autowired
       private FilterChainProxy filterChainProxy;
    
    
        @Before
        public void setUp() {
            MockitoAnnotations.initMocks(this);
            this.mockMvc = webAppContextSetup(wac).dispatchOptions(true).addFilters(filterChainProxy).build();
        }
    
    0 讨论(0)
提交回复
热议问题