Spring test MVC controller with @PreAuthorize giving 403 access denied

trying to write some integration test with a Spock structure for my controller that has @PreAuthorize annotation on it. When I launch the application, this tag works like a charm. However, when I run the integration test, I get 403.

My SecurityConfig.java :

 @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/test/**") .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .csrf().disable(); } @Bean @Override protected AuthenticationManager authenticationManager() { return new ProviderManager(Arrays.asList(getAuthenticationProvider())); } } 

My controller:

 @RestController @Validated @RequestMapping("/test") public class TestController { @PreAuthorize("hasPermission(#object, '')") @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE, headers = { "Accept=application/json", "Content-Type=application/json" }) public ResponseEntity<List<String>> testController(@RequestBody @Valid TestObject object, @RequestHeader(ACCOUNT) String account) throws ResourceNotFoundException, ServletRequestBindingException, MethodArgumentNotValidException, NoSuchMethodException, SecurityException { //return statement here!! } } 

and my PermissionEvaluator is as follows:

 @Component public class TestPermissionEvaluator implements PermissionEvaluator { private HttpServletRequest request; private TestRepository<AccountRoles> repository; @Override public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { AccountRole accountRole; TestObject object = (TestObject) targetDomainObject; try { accountRole = repository.find(object.getAccountID(), id); } catch (ResourceNotFoundException e) { // throw new Exception here } return true; } @Override public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) { return false; } } 

And finally, my test class looks like this:

 @ContextConfiguration(locations = ['file:src/main/webapp/WEB-INF/spring/testWebmvc-config.xml', 'file:src/main/webapp/WEB-INF/spring/appContext/servlet-context.xml']) @WebAppConfiguration public class TestControllerIntegration extends Specification { TestController controller MockMvc mockMvc @Inject WebApplicationContext wac @Inject ObjectMapper mapper @Autowired private FilterChainProxy filterChainProxy def setup() { controller = new TestController() mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(filterChainProxy).apply(SecurityMockMvcConfigurers.springSecurity()).build() SecurityContextHolder.clearContext() SecurityContextHolder.getContext().setAuthentication(new TestAuthenticationToken("145214741")) } @Unroll def 'valid post to /test'() { when: MvcResult result = mockMvc.perform(post('/test'). content(readJsonFromFile(jsonFileLocation)). contentType(APPLICATION_JSON). header('account', account). accept(APPLICATION_JSON)). andDo(print()). andReturn() then: def ids = mapper.readValue(result.response.getContentAsString(), List.class) } 

Every time I try to run this test, I get 403 with the following stacktrace command:

 MockHttpServletResponse: Status = 403 Error message = Access Denied Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]} Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = [] com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input at [Source: ; line: 1, column: 1] 

What I miss here, thanks in advance!

+4
java spring spring-mvc spring-security spock
source share

No one has answered this question yet.

See similar questions:

46
How to test spring-security-oauth2 resource server security?
7
Run unit tests on controllers requiring authentication

or similar:

2480
How do I send JSON data using Curl from a terminal / command line in Test Spring REST?
351
What is @ModelAttribute in Spring MVC?
333
Download file from spring controllers
306
Difference between spring @Controller and @RestController comments
237
Spring MVC @PathVariable with dot (.) Truncated
170
404 trigger in Spring-MVC controller?
162
Spring MVC - How to get all request parameters on a map in a Spring controller?
61
Can Spring use @PreAuthorize security in Spring controller methods?
2
Autowired bean is null in MVC Controller

All Articles