How to simulate the @PreAutorize tag in a integration test?

Viewed 1001

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)
3 Answers
Related