Тег Spring Security @Preauthorize не работает в модульном тесте - PullRequest
1 голос
/ 22 февраля 2012

(Во-первых, я прошу прощения, я не могу получить более одного уровня отступа для моего кода)

Я пытаюсь написать модульный тест для проверки моих методов уровня обслуживания.Интерфейс для этих классов обслуживания помечен @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 ().

Может кто-нибудь помочь?

Джейсон

1 Ответ

1 голос
/ 23 февраля 2012
  • Проводите ли вы модульное тестирование с помощью пружинного бегунка?
  • Указываете ли вы на правильный файл конфигурации пружины для этого модульного теста?
  • Вы настроили время загрузкипо аспектам безопасности?

Строка:

locationService = new LocationServiceImpl();

Создает новую службу определения местоположения, полностью минуя пружину.Если вы используете бегун spring junit, то вам следует использовать @Resource для инъекции locationService, чтобы вы использовали пружинный компонент, а не только свое pojo.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...