How does JUnit check the @PreAuthorize annotation and its spring EL defined by the MVC spring controller?

I defined this method in my Spring MVC controller:

@RequestMapping(value = "{id}/content", method=RequestMethod.POST) @PreAuthorize("principal.user.userAccount instanceof T(com.anonym.model.identity.PedagoAccount) AND principal.user.userAccount.userId == #object.pedago.userId AND #form.id == #object.id") public String modifyContent(@PathVariable("id") Project object, @Valid @ModelAttribute("form") ProjectContentForm form) { .... } 

Then, in my JUnit test, I would like to call this method and make sure the PreAuthorize condition is checked. But when I install the user principal in my JUnit test with a bad account, there is no error, and the method ends. Seems annotation annulled.
But when I call this method in the usual way (without testing), PreAuthorize is checked.

If possible, how to check this annotation in the junit test and how to catch an exception if it throws one?

Thank,
Nicolas

+10
spring-el spring-mvc spring-security junit controller
Mar 23 2018-11-11T00:
source share
1 answer

Since you want to test functions implemented using Spring AOP, you need to use the Spring TestContext to run the tests using the application context.

Then you create a basic test with a minimal security configuration:

abstract-security-test.xml :

 <security:authentication-manager alias="authenticationManager"> <security:authentication-provider user-service-ref = "userService" /> </security:authentication-manager> <security:global-method-security pre-post-annotations="enabled" /> <bean id = "userService" class = "..." /> 

AbstractSecurityTest.java :

 @ContextConfiguration("abstract-security-test.xml") abstract public class AbstractSecurityTest { @Autowired private AuthenticationManager am; @After public void clear() { SecurityContextHolder.clearContext(); } protected void login(String name, String password) { Authentication auth = new UsernamePasswordAuthenticationToken(name, password); SecurityContextHolder.getContext().setAuthentication(am.authenticate(auth)); } } 

Now you can use it in your tests:

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(...) public class CreatePostControllerSecurityTest extends AbstractSecurityTest { ... @Test @ExpectedException(AuthenticationCredentialsNotFoundException.class) public void testNoAuth() { controller.modifyContent(...); } @Test @ExpectedException(AccessDeniedException.class) public void testAccessDenied() { login("userWithoutAccessRight", "..."); controller.modifyContent(...); } @Test public void testAuthOK() { login("userWithAccessRight", "..."); controller.modifyContent(...); } } 
+15
Mar 23 '11 at 10:45
source share



All Articles