2017-06-29 125 views
0

我有一个项目,其中Spring与JSF一起使用(使用PrimeFaces)。到目前为止,我们已经为Spring Security使用了xml配置,但我的任务是将它移植到基于java的配置中。Spring Security登录处理URL不可用

我现在已经从XML配置进去applicationContext.xml

<!-- Security Config --> 
<security:http security="none" pattern="/javax.faces.resource/**"/> 
<security:http auto-config="true" use-expressions="true"> 
    <security:intercept-url pattern="/login.xhtml" access="permitAll"/> 
    <security:intercept-url pattern="/**" access="permitAll"/> 

    <security:form-login login-page="/login.xhtml" 
     login-processing-url="/do_login" 
     authentication-failure-url="/login.xhtml" 
     authentication-success-handler-ref="authSuccessHandler" 
     username-parameter="email" 
     password-parameter="password"/> 
    <security:logout logout-success-url="/login.xhtml" 
     logout-url="/do_logout" 
     delete-cookies="JSESSIONID"/> 
</security:http> 

<bean id="userDetails" class="com.madmob.madmoney.security.UserDetailsServiceImpl"></bean> 
<bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"> 
    <constructor-arg name="strength" value="10" /> 
</bean> 
<bean id="authSuccessHandler" class="com.madmob.madmoney.security.UserAuthenticationSuccessHandler"></bean> 

<security:authentication-manager> 
    <security:authentication-provider user-service-ref="userDetails"> 
     <security:password-encoder ref="encoder" />  
    </security:authentication-provider> 
</security:authentication-manager> 

,并从web.xml如下:

<filter> 
    <filter-name>springSecurityFilterChain</filter-name> 
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter> 
<filter-mapping> 
    <filter-name>springSecurityFilterChain</filter-name> 
    <url-pattern>/*</url-pattern> 
    <dispatcher>FORWARD</dispatcher> 
    <dispatcher>REQUEST</dispatcher> 
</filter-mapping> 

以下基于Java的配置:

import javax.sql.DataSource; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 
import org.springframework.security.config.annotation.web.builders.WebSecurity; 
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    UserAuthenticationSuccessHandler authSuccessHandler; 
    @Autowired 
    DataSource dataSource; 

    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) 
     throws Exception { 
     auth.jdbcAuthentication().usersByUsernameQuery("SELECT email, passowrd, enabled FROM app_user WHERE email = ?") 
     .authoritiesByUsernameQuery("SELECT role_name FROM role WHERE role_id = (SELECT role_id FROM user_role WHERE email = ?)") 
     .dataSource(dataSource).passwordEncoder(new BCryptPasswordEncoder(10)); 
    } 

    @Override 
    public void configure(WebSecurity web) throws Exception { 
     web.ignoring().antMatchers("/javax.faces.resource/**"); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.csrf().disable(); 

     http.authorizeRequests().anyRequest().authenticated() 
     .and() 
     .formLogin().loginPage("/login.xhtml").loginProcessingUrl("/do_login") 
     .failureUrl("/login.xhtml").successHandler(authSuccessHandler) 
     .usernameParameter("email").passwordParameter("password").permitAll() 
     .and() 
     .logout().logoutSuccessUrl("/login.xhtml").logoutUrl("/do_logout") 
     .deleteCookies("JSESSIONID"); 

     // temp user add form 
     // TODO remove 
     http.antMatcher("/userForm.xhtml").authorizeRequests().anyRequest().permitAll(); 
    } 
} 

import java.util.EnumSet; 

import javax.servlet.DispatcherType; 

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; 

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer { 

    protected EnumSet<DispatcherType> getSecurityDispatcherTypes() { 
     return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC, DispatcherType.FORWARD); 
    } 
} 

登录工作正常的基于XML的配置,但由于开关,如果我尝试登录的Tomcat返回404:The requested resource is not available.

所有页面也可以访问无论登陆与否。

下面是我的登录表单:

<h:form id="loginForm" prependId="false" styleClass="panel-body"> 
    <div> 
     <p:inputText id="email" required="true" label="email" 
        value="#{loginBean.email}" styleClass="form-control f-75" 
        placeholder="Email Address"></p:inputText> 
     <h:message for="email" styleClass="validationMsg"/> 
    </div> 
    <div class="spacer"/> 
    <div> 
     <p:password id="password" required="true" label="password" 
        value="#{loginBean.password}" placeholder="Password"></p:password> 
     <h:message for="password" styleClass="validationMsg"/> 

     <h:messages globalOnly="true" styleClass="validationMsg" /> 
    </div> 
    <div class="spacer"/> 
    <p:commandButton id="login" value="Log in" 
        actionListener="#{loginBean.login}" ajax="false"/> 
</h:form> 

,并在我的支持bean的登录方法:

/** 
* Forwards login parameters to Spring Security 
*/ 
public void login(ActionEvent loginEvt){ 
    // setup external context 
    logger.info("Starting login"); 
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); 

    // setup dispatcher for spring security 
    logger.info("Setup dispatcher"); 
    RequestDispatcher dispatcher = ((ServletRequest) context.getRequest()) 
      .getRequestDispatcher("/do_login"); 

    try { 
     // forward request 
     logger.info("Forwarding request to spring security"); 
     dispatcher.forward((ServletRequest) context.getRequest(), 
       (ServletResponse) context.getResponse()); 
    } catch (ServletException sEx) { 
     logger.error("The servlet has encountered a problem", sEx); 
    } catch (IOException ioEx) { 
     logger.error("An I/O error has occured", ioEx); 
    } catch (Exception ex) { 
     logger.error("An error has occured", ex); 
    } 

    // finish response 
    FacesContext.getCurrentInstance().responseComplete(); 
} 

这是关于Java 1.8,Tomcat的7,Spring和Spring Security的3.2.5运行,JSF 2.1,Primefaces 5

自从遇到问题以来我试过的东西:

  • 添加了SpringSecurityInitializer,因为最初我只使用了SecurityConfig
  • 尝试使用默认的Spring Security url(j_spring_security_check),通过不指定处理url并转发给它。
  • 残疾人CSRF
  • 新增getSecurityDispatcherTypes方法SpringSecurityInitializer到配置从web.xml中
  • 各种其他的小东西,同时寻找解决的办法
+0

你引导Spring Security没有任何配置。您应该调用AbstractSecurityWebApplicationInitializer(类 ...configurationClasses)'构造函数而不是默认的无参数构造函数。或者,如果您有另一种加载'ContextLoaderListener'的方法,则将配置类添加到该类中。 –

+0

'ContextLoaderListener'在我的'web.xml'中定义,所以如果我调用该构造函数,则会得到一个异常,因为已经有一个根应用程序上下文,我不知道如何才能添加配置。请注意,据我所知,'@ EnableWebSecurity'注解应该处理这个问题,还是我错过了一些东西? (该软件包是组件扫描的一部分,但我也在使用xml手动定义bean时遇到同样的问题) – Vinc

+0

如果您的配置未加载,您可以根据需要放置尽可能多的注释,而不会产生任何影响。因此,请确保配置已加载(尽管某些内容已被加载,否则,您的应用将无法启动一条消息,指出名为'springSecurityFilterChain'的bean未定义)。 –

回答

0

我发现这个问题相匹配。问题在于:

http.antMatcher("/userForm.xhtml").authorizeRequests().anyRequest().permitAll(); 

这只是我的方法纯粹错误的链接的外观。我真的不明白为什么它造成了登录处理URL的问题没有被发现,而不是仅仅意外访问行为,但我改变了该方法的整个片段看起来如下:

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http.csrf().disable() 
    .authorizeRequests().antMatchers("/userForm.xhtml").permitAll() //TODO remove temp user add form 
    .anyRequest().authenticated() 
    .and() 
    .formLogin().loginPage("/login.xhtml").loginProcessingUrl("/do_login") 
    .failureUrl("/login.xhtml").successHandler(authSuccessHandler) 
    .usernameParameter("email").passwordParameter("password").permitAll() 
    .and() 
    .logout().logoutSuccessUrl("/login.xhtml").logoutUrl("/do_logout") 
    .deleteCookies("JSESSIONID"); 
} 

当然,这也更有意义,但我最初主要将它们分开,因为按照注释说明,userForm.xhtml是暂时的。