我有一個項目,其中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中 - 各種其他的小東西,同時尋找解決的辦法
你引導Spring Security沒有任何配置。您應該調用AbstractSecurityWebApplicationInitializer(類> ...configurationClasses)'構造函數而不是默認的無參數構造函數。或者,如果您有另一種加載'ContextLoaderListener'的方法,則將配置類添加到該類中。 –
'ContextLoaderListener'在我的'web.xml'中定義,所以如果我調用該構造函數,則會得到一個異常,因爲已經有一個根應用程序上下文,我不知道如何才能添加配置。請注意,據我所知,'@ EnableWebSecurity'註解應該處理這個問題,還是我錯過了一些東西? (該軟件包是組件掃描的一部分,但我也在使用xml手動定義bean時遇到同樣的問題) – Vinc
如果您的配置未加載,您可以根據需要放置儘可能多的註釋,而不會產生任何影響。因此,請確保配置已加載(儘管某些內容已被加載,否則,您的應用將無法啓動一條消息,指出名爲'springSecurityFilterChain'的bean未定義)。 –