How to JUnit tests a @PreAuthorize annotation and its spring EL specified by a spring MVC Controller?

Nico picture Nico · Mar 23, 2011 · Viewed 13.5k times · Source

I've 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'd like to call this method and ensure that the PreAuthorize condition is verified. But when I set the user principal in my JUnit test with a bad account there is no error and the method completes. It seems the annotation is bypassed.
But when I call this method in a normal way (not testing), the PreAuthorize is verified.

If it's possible, how to test this annotation in a junit test and how to catch the exception if it throws one ?

Thanks,
Nicolas

Answer

axtavt picture axtavt · Mar 23, 2011

Since you want to test features implemented via Spring AOP, you need to use Spring TestContext framework to run tests against application context.

Then you create a base test with 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(...);
    }
}