2015-06-24 5 views
1

пожалуйста, может кто-нибудь помочь мне с переходом от x Spring на основе Spring на java?spring security config xml to java

вот мой XML конфигурации:

<!--suppress SpringFacetInspection, SpringSecurityFiltersConfiguredInspection --> 
<beans:beans xmlns="http://www.springframework.org/schema/security" 
      xmlns:beans="http://www.springframework.org/schema/beans" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xmlns:context="http://www.springframework.org/schema/context" 
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
           http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 


    <global-method-security pre-post-annotations="enabled"/> 
    <context:annotation-config/> 
    <context:spring-configured/> 


    <beans:bean name="userLoginService" class="service.UserLoginService"/> 

    <beans:bean name="standardPasswordEncoder" 
       class="org.springframework.security.crypto.password.StandardPasswordEncoder"> 
     <beans:constructor-arg name="secret" value="supersecret"/> 
    </beans:bean> 

    <http auto-config="true" use-expressions="true"> 
     <intercept-url pattern="/javax.faces.resources/**" access="permitAll"/> 
     <intercept-url pattern="/view/unsecured/**" access="permitAll"/> 
     <intercept-url pattern="/view/secured/**" access="isAuthenticated()" /> 
     <intercept-url pattern="/view/admin/**" access="hasRole('ROLE_SUPERUSER')"/> 
     <intercept-url pattern="/admin/**" access="hasRole('ROLE_SUPERUSER')"/> 

     <form-login login-page="/view/unsecured/login.xhtml"/> 
     <logout logout-success-url="/index.xhtml" invalidate-session="true" delete-cookies="true"/> 
    </http> 

    <authentication-manager alias="authenticationManager"> 
     <authentication-provider user-service-ref="userLoginService"> 
      <password-encoder ref="standardPasswordEncoder"/> 
     </authentication-provider> 
    </authentication-manager> 

</beans:beans> 

и вот моя ява попытка:

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Bean(name = "standardPasswordEncoder") 
    public PasswordEncoder standardPasswordEncoder() { 
     return new StandardPasswordEncoder("supersecret"); 
    } 

    @Bean(name = "userDetailService") 
    @Override 
    public UserDetailsService userDetailsServiceBean() { 
     return new UserLoginService(); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
       //.userDetailsService(userDetailsService()) 
       .authorizeRequests() 
       .antMatchers("/view/secured/**").fullyAuthenticated() 
       .antMatchers("/admin/**", "/view/admin/**").access("hasRole('ROLE_SUPERUSER')") 
       .antMatchers("/index.xhtml", "/view/unsecured/**", "/javax.faces.resources/**").permitAll() 
       .and() 
       .formLogin().loginPage("/view/unsecured/login.xhtml") 
       .usernameParameter("email").passwordParameter("password") 
       .and() 
       .logout().logoutSuccessUrl("/index.xhtml").invalidateHttpSession(true).deleteCookies("JSESSIONID") 
       .and() 
       .exceptionHandling().accessDeniedPage("/error.xhtml") 
       .and() 
       .csrf().disable(); 
    } 

    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth.userDetailsService(userDetailsService()).passwordEncoder(standardPasswordEncoder()); 
    } 
} 

При попытке войти я получаю Exception

Caused by: java.lang.StackOverflowError: null 
     at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$UserDetailsServiceDelegator.loadUserByUsername(WebSecurityConfigurerAdapter.java:386) 
     at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$UserDetailsServiceDelegator.loadUserByUsername(WebSecurityConfigurerAdapter.java:387) 
... 

Что я упускаю , или что не так? Thanks

ответ

3

Переопределить метод userDetailsService(), а не метод userDetailsServiceBean(). Вот что вызывает бесконечную рекурсию. И не нужно объявлять это как @Bean.

должен быть просто:

@Override 
public UserDetailsService userDetailsService() { 
    return new UserLoginService(); 
} 

В качестве альтернативы - если у вас есть @Service аннотацию на ваш UserLoginService (и компонент сканирования, который подберет этот класс), вы можете избежать создания вручную бобы и просто вводить свой UserLoginService прямо в ваш метод конфигурации:

@Autowired 
public void configureGlobal(AuthenticationManagerBuilder auth, UserLoginService userDetailsService) throws Exception { 
    auth.userDetailsService(userDetailsService).passwordEncoder(standardPasswordEncoder()); 
} 

Тогда вам не нужно будет переопределить userDetailsServiceBean или userDetailsService: поскольку все, что они делают, создает экземпляр этого компонента.

+0

Спасибо, это мне помогло. У меня есть еще один вопрос. С помощью xml config я использовал свой loginAction() в управляемом компоненте после нажатия кнопки входа в систему. Теперь это действие не отменено, но я вижу, что вызывается UserLoginService. Вы знаете, что делать, чтобы снова вызвать свое действие? – bilak

+0

Хорошо, мне это удалось. Я удалил .loginPage («/ view/unsecured/login.xhtml») .usernameParameter («email»). ПарольПараметр («пароль») – bilak