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.
<security:global-method-security pre-post-annotations="enabled" >
<security:expression-handler ref="expressionHandler"/>
</security:global-method-security>
<beans:bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<beans:property name="permissionEvaluator" ref="permissionEvaluator"/>
</beans:bean>
Check spring-testcontext-framework and this post answering question very similar to yours.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With