2014-01-28 3 views
0

Использование Spring MVC 3.2 с Spring Security 3.1Mocking Spring менеджер глобальной аутентификации

Target контейнере JBoss 4 (не спрашивайте), так сервлет API еще 2,4. При тестировании конфигурации безопасности Spring она записывается в XML и вставляется в web.xml с кучей других вещей. Думал, что я напишу небольшой тестовый слой JUnit, который издевается над основным запросом и вызывает проверку подлинности проверки безопасности Spring. Идея заключалась в том, чтобы помочь другим разработчикам проверить конфигурацию безопасности, прежде чем интегрировать ее в остальную часть проекта.

Во всяком случае, если я не определить менеджера аутентификации в XML безопасности я получаю:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.security.authenticationManager' is defined: Did you forget to add a gobal <authentication-manager> element to your configuration (with child <authentication-provider> elements)? Alternatively you can use the authentication-manager-ref attribute on your <http> and <global-method-security> elements. 

Мой тест JUnit класс выглядит следующим образом:

@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@ContextConfiguration(classes = {LdapSecurityTest.WebAppConfig.class, 
    LdapSecurityTest.WebSecurityConfig.class}) 
public class LdapSecurityTest { 

    @Controller 
    public static class DummyController { 
     @RequestMapping(value = "/blankettservice/admin/test", method = RequestMethod.GET) 
     @ResponseBody 
     public String hello() { 
      return "hello world"; 
     } 
    } 

    @EnableWebMvc 
    @Configuration 
    @ComponentScan("se.bolagsverket.insidan.web.common") 
    public static class WebAppConfig { 
    } 

    @Configuration 
    @ImportResource({"classpath:applicationContext-security.xml"}) 
    public static class WebSecurityConfig { 
     @Autowired 
     private List<AuthenticationProvider> providers; 

     @Bean 
     public AuthenticationManager authenticationManager() { 
      return new ProviderManager(providers); 
     } 
    } 

    public class SpringInitializer implements WebApplicationInitializer { 

     @Override 
     public void onStartup(ServletContext servletContext) 
      throws ServletException { 
      AnnotationConfigWebApplicationContext ctx = 
       new AnnotationConfigWebApplicationContext(); 

      ServletRegistration.Dynamic dispatcher = 
       servletContext.addServlet("dispatcher", new DispatcherServlet(
        ctx)); 
      dispatcher.setLoadOnStartup(1); 
      dispatcher.addMapping("/"); 

      servletContext.addFilter("springSecurityFilterChain", 
       new DelegatingFilterProxy("springSecurityFilterChain")) 
       .addMappingForUrlPatterns(null, false, "/*"); 
     } 
    } 

    @Resource 
    private WebApplicationContext context; 

    @Test 
    public void initialize() throws Exception { 

     SecurityContextHolder.getContext().setAuthentication(
      new UsernamePasswordAuthenticationToken("user", "password")); 

     MockMvc mvc = webAppContextSetup(context).build(); 

     mvc.perform(get("/blankettservice/admin/test")).andExpect(status().isOk()) 
      .andExpect(content().string("hello world")); 
     ; 
    } 
} 

Просто для ясности ApplicationContext-безопасности выглядит следующим образом:

<http> 
     <intercept-url pattern="/**/blankettservice/admin/**" 
      access="ROLE_BLANKETTSERVICE_ADMIN" /> 
     <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" /> 
     <http-basic /> 
     <anonymous /> 
    </http> 

    <beans:bean id="contextSource" 
     class="org.springframework.security.ldap.DefaultSpringSecurityContextSource"> 
     <beans:constructor-arg value="ldap://server:port" /> 
     <beans:property name="userDn" value="..." /> 
     <beans:property name="password" value="..." /> 
    </beans:bean> 

    <beans:bean id="bvLdapAuthProvider" class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider> 
    .... 
    </beans:bean> 

Бранд-провайдер ProviderManager, который создан populat ed с поставщиком bvLdapAuthProvider.

+0

Если я добавлю имя «org.springframework.security.authenticationManager» в мой компонент AuthenticationManager, тогда ошибка исчезнет. –

+0

Никогда не получает отказано в доступе. Это проблема сейчас. Посмотрите, что мой провайдер авторизации запущен, нет никакого соединения с HTTP-перехватом-url против «/ blankettservice/admin/test». –

+0

Фильтр безопасности пружины никогда не инициализируется. Также не позвонил мой провайдер авторизации LDAP (инициализирован да, но не вызван для аутентификации). –

ответ

0

В нашей конфигурации (Spring Security 3) для LDAP мы используем этот конфиг:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:security="http://www.springframework.org/schema/security" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:jdbc="http://www.springframework.org/schema/jdbc" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/security 
     http://www.springframework.org/schema/security/spring-security-3.1.xsd 
     http://www.springframework.org/schema/jdbc 
     http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd"> 

... 

<security:authentication-manager> 
    <security:ldap-authentication-provider user-dn-pattern="uid={0},ou=people"/> 
</security:authentication-manager> 
<security:ldap-server url="ldap://localhost:10389/dc=example,dc=com" /> 

... 

Надеется, что это помогает.

+0

У вас уже есть поставщик проверки подлинности. Не нужно создавать новую. Моя проблема - тест. –

Смежные вопросы