title: In Springboot Unit test, MockMvc returns 403 Forbidden
body: <p>In Springboot unit Test always return 403 error,I've tried a variety of different configurations using AutoConfigureMockMvc with secure false and excluding security auto configuration getting 403 errror. Can anyone help me on this.</p>
  <p>Here is my Security Implementation</p>
  <pre><code>@Configuration
  @EnableWebSecurity
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Resource(name = &quot;userService&quot;)
      private UserDetailsService userDetailsService;
  
      @Override
      @Bean
      public AuthenticationManager authenticationManagerBean() throws Exception {
          return super.authenticationManagerBean();
      }
  
      @Autowired
      public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
          auth.authenticationEventPublisher(authenticationEventPublisher())
                  .userDetailsService(userDetailsService)
                  .passwordEncoder(encoder());
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.csrf()
                  .disable()
                  .anonymous()
                  .disable()
                  .authorizeRequests()
                  .antMatchers(&quot;/api-docs/**&quot;)
                  .permitAll();
      }
  
      @Bean
      public DefaultAuthenticationEventPublisher authenticationEventPublisher() {
          return new DefaultAuthenticationEventPublisher();
      }
  
      @Bean
      public TokenStore tokenStore() {
          return new InMemoryTokenStore();
      }
  
      @Bean
      public BCryptPasswordEncoder encoder() {
          return new BCryptPasswordEncoder();
      }
  
      @Bean
      public FilterRegistrationBean corsFilter() {
          UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
          CorsConfiguration config = new CorsConfiguration();
          config.setAllowCredentials(true);
          config.addAllowedOrigin(&quot;*&quot;);
          config.addAllowedHeader(&quot;*&quot;);
          config.addAllowedMethod(&quot;*&quot;);
          source.registerCorsConfiguration(&quot;/**&quot;, config);
          FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
          bean.setOrder(0);
          return bean;
      }
     }
  </code></pre>
  <p>Sharing Api Implementation Class,  added PreAuthorize -Admin, to view all users</p>
  <pre><code>@RestController
  @RequestMapping(&quot;/api/userInfo&quot;)
  public class UserController {
  
      private final Logger LOG = Logger.getLogger(getClass());
  
      private String serviceMsg = &quot;serviceMsg&quot;;
  
      @Autowired
      private UserService userService;
  
      @Autowired
      private UserServiceUtil util;
  
      
      @PreAuthorize(&quot;hasAnyRole('ADMIN')&quot;)
      @RequestMapping(method = RequestMethod.GET, produces = &quot;application/json&quot; )
      @ApiOperation(value = &quot;Get details of all RA2 users in a paginated JSON format&quot;)
      public Page&lt;User&gt; listUser(Pageable pageable) {
          return userService.getUserSummary(pageable);
      }
  </code></pre>
  <p>And Here is my JUnit Test ,am Sending get request and return 403 error.</p>
  <pre><code>@RunWith(SpringRunner.class)
  @SpringBootTest
  @ActiveProfiles(&quot;test&quot;)
  @ContextConfiguration
  @AutoConfigureMockMvc(addFilters = false)
  
  public class UserControllerTest {
      
      @Configuration
      
      @EnableGlobalMethodSecurity(prePostEnabled = true)
      protected static class TestConfiguration {
           @Bean
           @Primary
           public UserService getUserService(){
                 return Mockito.mock(UserService.class);
           }
           
           @Bean
           @Primary
           public UserServiceUtil getUserServiceUtil(){
                 return Mockito.mock(UserServiceUtil.class);
           }
      }
      @Autowired
      private MockMvc mockMvc;
      
      @Autowired
      private WebApplicationContext webApplicationContext ;
  
      
      
      private String serviceMsg = &quot;serviceMsg&quot;;
  
      @Autowired
      private UserService userService;
  
      @Autowired
      private UserServiceUtil util;
      
      private User admin;
      private User user;
      
      @Before
      public void setup() {
  
          mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext ).apply(springSecurity()).build();
          }
  
      @WithMockUser(username = &quot;test&quot;,authorities =&quot;ADMIN&quot;)
      @Test
      public void getuserList() throws Exception {
          List&lt;User&gt; list = new ArrayList&lt;User&gt;();
          list.add(new User());
          Page&lt;User&gt; page = new PageImpl&lt;User&gt;(list, null, list.size());
          Mockito.when(userService.getUserSummary(any(Pageable.class))).thenReturn(page);
          this.mockMvc.perform(get(&quot;/api/userInfo?page=1&amp;size=10&quot;).with(csrf()).contentType(MediaType.APPLICATION_JSON)).
          andExpect(status().isOk()).andDo(MockMvcResultHandlers.print());
        }
      ```
  </code></pre>