(First, I apologize, I can’t get more than a single level of indention for my code)
I am attempting to write a unit test to test my service-layer methods. The interface for these service classes are annotated with @Preauthorize:
public interface LocationService {
void setLocationRepository(LocationRepository locationRepository);
/**
* Get all Location objects from the backend repository
* @return
*/
@PreAuthorize("has_role('ROLE_ADMIN')")
List<Location> getAll();
The unit test looks something like this:
@Before
public void setUp() {
admin = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("admin", "admin"));
user = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "user"));
// create Mock Repository
// set up the actual service WITH the repository
locationService = new LocationServiceImpl();
locationService.setLocationRepository(locationRepository);
}
@Test(expected = AccessDeniedException.class)
@SuppressWarnings("unused")
public void testGetAllAsUser() {
SecurityContextHolder.getContext().setAuthentication(user);
List<Location> resultList = locationService.getAll();
}
Finally, here is the security context from my applicationContext.xml:
<!-- Temporary security config. This will get moved to a separate context
file, but I need it for unit testing right now -->
<security:http use-expressions="true">
<security:form-login />
<security:session-management
invalid-session-url="/timeout.jsp">
<security:concurrency-control
max-sessions="1" error-if-maximum-exceeded="true" />
</security:session-management>
</security:http>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider>
<security:password-encoder hash="plaintext" />
<security:user-service>
<security:user name="admin" password="admin"
authorities="ROLE_ADMIN" />
<security:user name="user" password="user"
authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
<security:global-method-security
pre-post-annotations="enabled" proxy-target-class="true" />
Unfortunately, the @PreAuthorize tag is being ignored, allowing someone with ROLE_USER to run getAll().
Can anyone help?
Jason
The line:
Creates a new location service, bypassing spring altogether. If you are using the spring junit runner then you should use @Resource to get the locationService injected so that you are using the spring bean and not just your pojo.