(Во-первых, я прошу прощения, я не могу получить более одного уровня отступа для моего кода)
Я пытаюсь написать модульный тест для проверки моих методов уровня обслуживания.Интерфейс для этих классов обслуживания помечен @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();
Модульный тест выглядит примерно так:
@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();
}
Наконец, вот контекст безопасности из моего 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" />
К сожалению, тег @PreAuthorize игнорируется, что позволяет кому-то с ROLE_USER запускать getAll ().
Может кто-нибудь помочь?
Джейсон