Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 853
Thomas Vervik Avatar asked Aug 20 '12 08:08

Thomas Vervik


1 Answers

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.

like image 174
Jeevan Patil Avatar answered Nov 18 '22 21:11

Jeevan Patil