I have the following method in Spring MVC and using Spring Security:
@PreAuthorize("#phoneNumber == authentication.name")
@RequestMapping(value = "/{phoneNumber}/start", method = RequestMethod.POST)
public ModelAndView startUpgrading(@PathVariable("phoneNumber") String phoneNumber,
....
}
I manage to simulate authentication something like this:
public Authentication tryToAuthenticate(String accountName, String password) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(accountName, password);
return authenticationManager.authenticate(token);
}
But I dont know how to set up the authorization with @PreAutorize.
How can I set up my test context correctly such that I dont get access denied ?
org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:205)
The annotations ( @PreAuthorize, @PostAuthorize, @PreFilter, @PostFilter ) which support expression attributes to allow pre & post-invocation authorization checks are enabled through the global-method-authority namespace element.
You need to add following code in your application-servlet.xml or security xml file.
Check spring-testcontext-framework and this post answering question very similar to yours.