使用JSF的Spring Secuirty,提交后重新加载同一页面

时间:2017-06-16 07:22:08

标签: spring jsf spring-security

我正在使用Spring Security& JSF。提交登录时,页面重新加载没有任何反应,action="${pageContext.request.contextPath}/j_spring_security_check"没有被调用。

请帮忙。先感谢您。

以下是我的网页和配置:

login.xhtml:

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:a4j="http://richfaces.org/a4j"
    xmlns:rich="http://richfaces.org/rich"
    xmlns:cls="http://emia.com/emia/ui"
    xmlns:cat360="http://java.sun.com/jsf/composite/components">
    <ui:composition template="/templates/login/loginTemplate.xhtml">

        <ui:define name="body">

            <h:outputStylesheet>  
                .panelGridValign td {     vertical-align: top !important; } 
                .rf-p-hdr{ 
                    height: 15  px !important;
                    display: block  !important;
                    border: none  !important;
                    background: url("${facesContext.externalContext.requestContextPath}/images/menuBg.jpg") repeat-x 0 0 !important;
                    padding:5px 5px 5px 5px !important;
                    color : #ffffff !important
                }
                .topalgn {
                    vertical-align: top;
                }   


                #menu-nav {
                    background: #fff url("${facesContext.externalContext.requestContextPath}/images/menuBg.jpg") repeat-x 0 0;
                    height: 30px;
                    padding: 0;
                    display: block;
                    border: none
                }           
                .content {
                    padding: 0px !important;
                    min-height: 0px !important;
                }   

    </h:outputStylesheet>

            <f:event listener="#{loginBean.updateMessages}" type="preRenderView" />

            <div class="contentBg">
                <div id="menu-nav"></div>
                <div class="wrapper">

                    <div class="content">

                        <div class="logInSection">
                            <div class="leftBlock">
                                <h2>Welcome to Nomad</h2>
                                <h:graphicImage library="images" url="#{loginBean.loginPageImage}"/>

                            <div class="rightBlock">
                                <h3>Login</h3>
                                <div class="rightLoginBlock">
                                    <h:form id="loginForm" prependId="false"
                                        action="${pageContext.request.contextPath}/j_spring_security_check">

                                        <table cellpadding="0" cellspacing="0" width="99%">
                                            <tbody>

                                                <tr>
                                                    <td class="labelClass1">User Name</td>
                                                    <td class="fieldClass"><h:inputText id="j_username"
                                                            required="true" requiredMessage="Username is mandatory"
                                                            style=" width :150px;">
                                                        </h:inputText></td>
                                                </tr>
                                                <tr>
                                                    <td class="labelClass1">Password</td>
                                                    <td class="fieldClass"><h:inputSecret id="j_password"
                                                            required="true" requiredMessage="Password is mandatory"
                                                            styleClass="form_input" style=" width :150px;">
                                                        </h:inputSecret></td>
                                                </tr>
                                                <tr>
                                                    <td class="labelClass1">Company</td>
                                                    <td class="fieldClass"><h:selectOneMenu
                                                            id="loginCompany" value="#{loginBean.selectedCompany}"
                                                            disabled="#{!loginBean.multiHosted}" required="true"
                                                            requiredMessage="Company is mandatory"
                                                            styleClass="form_select" style=" width :50px;">
                                                            <f:selectItems value="#{loginBean.companyCodeList}"></f:selectItems>
                                                            <f:ajax listener="#{loginBean.companySelected}"
                                                                render="loginSite" event="change" execute="@this" />

                                                        </h:selectOneMenu> <h:inputHidden value="#{loginBean.selectedCompany}"
                                                            id="loginCompanyHidden" /></td>
                                                </tr>
                                                <tr>
                                                    <td class="labelClass1">Site</td>
                                                    <td class="fieldClass"><h:selectOneMenu id="loginSite"
                                                            value="#{loginBean.selectedSite}" required="true"
                                                            requiredMessage="Site is mandatory"
                                                            styleClass="form_select" style=" width :50px;">

                                                            <f:selectItems value="#{loginBean.siteCodeList}"></f:selectItems>
                                                        </h:selectOneMenu></td>
                                                </tr>
                                                <tr>
                                                    <td class="labelClass1"></td>
                                                    <td align="right" class="fieldClass"><span
                                                        style="text-align: right; float: right;"> <h:commandButton
                                                                type="submit" id="login"
                                                                onclick="loginTest(); return false;" value="login"
                                                                styleClass="submitButton" /> <br /> <br />
                                                                 <a4j:commandLink
                                                                    styleClass="forgetPass" value="Forgot Password?">
                                                                    <rich:componentControl target="forgotPasswordPopup"
                                                                        operation="show" event="click" />
                                                                </a4j:commandLink>

                                                    </span></td>
                                                </tr>
                                                <tr>
                                                    <td colspan="2" class="labelClass1"><a4j:outputPanel
                                                            id="loginErrorOutPanel" ajaxRendered="true"
                                                            styleClass="error" width="250px">

                                                            <h:panelGrid id="loginErrorPanel" width="250px">
                                                                <h:messages errorClass="error" infoClass="info" />
                                                            </h:panelGrid>
                                                        </a4j:outputPanel></td>
                                                </tr>
                                            </tbody>
                                        </table>

                                    </h:form>
                                </div>
                                <div class="shadow"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>


            <a4j:jsFunction name="clearSessionContext"
                action="#{loginBean.clearSessionContext}">
            </a4j:jsFunction>

            <a4j:jsFunction name="loginTest" action="#{loginBean.validateLogin}"
                oncomplete="submitForm(); return false;"
                render="loginErrorOutPanel,loginErrorPanel">
            </a4j:jsFunction>

        <script>
                // To focus on page startup
                jQuery(document).ready(function(){ 
                    clearSessionContext();
                  jQuery("#j_username").focus(); 
                });

                // Submitting the form on press enter
                jQuery(document).ready(jQuery('html').bind('keypress', function(e) 
                {      
                    if(e.keyCode == 13)      
                    {          
                        clearSessionContext();
                        loginTest();
                        //submitForm();

                    } 
                }));            
                // does the validation and submits the form
                function submitForm() {
                    var validationMsg = '';

                    if(jQuery("#j_username").val().length == 0) {
                        validationMsg = "Please enter the User Name";
                    }
                    if(jQuery("#j_password").val().length == 0) {
                        validationMsg += "\nPlease enter the Password";

                    }

                    if(jQuery("#loginCompany").val().length == 0) {
                        validationMsg += "\nPlease enter the Company";

                    }

                    if(jQuery("#loginSite").val().length == 0) {
                        validationMsg += "\nPlease enter the Site";

                    }



                    if (validationMsg.length == 0) {
                        document.loginForm.action = "${facesContext.externalContext.requestContextPath}/j_spring_security_check";
                        document.loginForm.submit();
                    }

                }

                function resetForm() {
                    document.loginFormId.reset();
                }
            </script>

        </ui:define>

    </ui:composition>
</ui:composition>

SSO-context.xml中:

<?xml version="1.0" encoding="UTF-8"?>
<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:p="http://www.springframework.org/schema/p"
    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-4.0.xsd">

    <!-- TODO: Import META-INF/spring/spring-security-mandatory.xml. Copy this 
        entry from the solution -->

    <beans:import resource="web-security-context.xml" />

    <http pattern="/login/**" security="none" />
    <http pattern="/pages/login/**" security="none" />
    <http pattern="/css/**" security="none" />
    <http pattern="/images/**" security="none" />
    <http pattern="/rfRes/**" security="none" />
    <http pattern="/resources/**" security="none" />
    <http pattern="/javax.faces.resource/**" security="none" />
    <http pattern="/js/*" security="none" />
    <http pattern="/pages/login/login.jsf" security="none" />
    <http pattern="/logout.xhtml" security="none" />
    <!-- <http pattern="/newlogin.jsp" security="none" /> -->
    <http pattern="/logout.jsp" security="none" />
    <http pattern="/error.jsp" security="none" />
    <http pattern="/favicon.ico" security="none" />
    <!-- <http pattern="/templates/**" security="none" /> -->
    <!-- <http pattern="/index.html" security="none" /> <http pattern="/index.xhtml" 
        security="none" /> -->

    <http use-expressions="false" auto-config="false" entry-point-ref="authenticationEntryPoint">
        <intercept-url pattern="/j_spring_security_check"
            access="IS_AUTHENTICATED_ANONYMOUSLY" />
        <intercept-url pattern="/j_spring_security_logout"
            access="IS_AUTHENTICATED_ANONYMOUSLY" />
        <intercept-url pattern="/pages/login/login.jsf" access="IS_AUTHENTICATED_ANONYMOUSLY" />
        <intercept-url pattern="/help/**" access="IS_AUTHENTICATED_FULLY" />
        <intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY" />
        <custom-filter position="CONCURRENT_SESSION_FILTER" ref="concurrencyFilter" />
        <!-- <custom-filter ref="hdivValidationFilter" before="SECURITY_CONTEXT_FILTER" /> -->
        <custom-filter ref="sessionManagementFilter" before="SESSION_MANAGEMENT_FILTER" />
        <custom-filter ref="basicAuthenticationFilter" after="BASIC_AUTH_FILTER" />
        <custom-filter ref="applicationSessionFilter" before="FORM_LOGIN_FILTER" />
        <custom-filter ref="applicationUsernamePasswordAuthProcessingFilter"
        position="FORM_LOGIN_FILTER" />         
        <logout logout-url="/j_spring_security_logout"
            invalidate-session="true" success-handler-ref="logoutSuccessHandler" />
    </http>

    <!-- <beans:bean id="hdivValidationFilter"
        class="org.hdiv.filter.ValidatorFilter">
    </beans:bean> -->


    <beans:bean id="authenticationEntryPoint"
        class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
        <beans:constructor-arg name="loginFormUrl" value="/pages/login/login.jsf" />
    </beans:bean>

    <beans:bean id="sessionManagementFilter"
        class="org.springframework.security.web.session.SessionManagementFilter">
        <beans:constructor-arg name="securityContextRepository"
            ref="httpSessionSecurityContextRepository" />

        <!-- this permits redirection to session timeout page from javascript/ajax 
            or http -->
        <beans:property name="invalidSessionStrategy" ref="jsfRedirectStrategy" />
    </beans:bean>

    <beans:bean id="jsfRedirectStrategy"
        class=".admin.security.JsfSessionTimeoutStrategy">
        <beans:constructor-arg name="invalidSessionUrl"
            value="/pages/login/login.jsf" />
    </beans:bean>

    <beans:bean id="httpSessionSecurityContextRepository"
        class="org.springframework.security.web.context.HttpSessionSecurityContextRepository" />

    <beans:bean id="basicAuthenticationFilter"
        class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter">
        <beans:constructor-arg name="authenticationManager" ref="authenticationManager" />
        <beans:constructor-arg name="authenticationEntryPoint" ref="authenticationEntryPoint" />
    </beans:bean>

    <beans:bean id="applicationUsernamePasswordAuthProcessingFilter"
        class=".admin.security.applicationUserNamePasswordFilter">

        <beans:property name="authenticationManager" ref="authenticationManager" />
        <beans:property name="filterProcessesUrl" value="/j_spring_security_check" />

        <beans:property name="authenticationSuccessHandler"
            ref="defauthenticationSuccessHandler" />
        <beans:property name="authenticationFailureHandler"
            ref="defauthenticationFailureHandler" />

    </beans:bean>

    <beans:bean id="defauthenticationSuccessHandler"
        class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"
        p:alwaysUseDefaultTargetUrl="false" p:defaultTargetUrl="/index.jsp" />

    <!-- <beans:bean id="defauthenticationSuccessHandler" class=".admin.security.applicationAuthenticationSuccessHandler" 
        p:alwaysUseDefaultTargetUrl="false" > <beans:property name="defaultTargetUrl" 
        value="/index.jsp" /> </beans:bean> -->


    <!-- <beans:bean id="defauthenticationFailureHandler" class=".admin.security.applicationAuthenticationFailureHandler" 
        p:defaultFailureUrl="/newlogin.jsp?login_error=1"> <beans:property name="redirectPage" 
        value="/newlogin.jsp" /> <beans:property name="contextRelative" value="true" 
        /> </beans:bean> -->

    <beans:bean id="defauthenticationFailureHandler"
        class=".admin.security.applicationAuthenticationFailureHandler"
        p:defaultFailureUrl="/pages/login/login.jsf?login_error=1">
    </beans:bean>

    <authentication-manager alias="authenticationManager">
        <!-- <authentication-provider ref="cmsAuthenticationProvider" /> -->
        <authentication-provider user-service-ref="applicationLoginService" />  <!-- for form-login -->
        <!-- <authentication-provider ref="kerberosServiceAuthenticationProvider" 
            /> -->
        <authentication-provider ref="rememberMeAuthenticationProvider" />
    </authentication-manager>

    <!-- This ensures that remember-me is added as an authentication provider -->
    <!-- <beans:bean id="rememberMeAuthenticationProvider" class=".admin.security.applicationAuthenticationProvider"> 
        </beans:bean> -->

    <beans:bean id="rememberMeAuthenticationProvider"
        class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="userDetailsService" ref="applicationLoginService" />

    </beans:bean>


    <beans:bean id="logoutSuccessHandler"
        class="org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler">
        <beans:property name="defaultTargetUrl" value="/pages/login/login.jsf?login_error=2" />
    </beans:bean>

    <beans:bean class=".admin.security.applicationSessionFilter"
        id="applicationSessionFilter">
        <beans:constructor-arg name="securityContextRepository"
            ref="httpSessionSecurityContextRepository" />
        <beans:constructor-arg name="invalidSessionStrategy"
            ref="jsfRedirectStrategy" />
    </beans:bean>


</beans:beans>

LoginBean.java:

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.model.SelectItem;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.web.WebAttributes;

@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean implements Serializable {

    private Logger LOGGER = LoggerFactory.getLogger(getClass());
    private String username = "";
    private String password = "";
    private String company = "";
    private String login;

    public String login() {

        try {

            LOGGER.debug("Login initiated....");

            ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();

            HttpServletRequest request = (HttpServletRequest) context.getRequest();

            if (validateLoginRequest(request)) {
                RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
                    .getRequestDispatcher("/j_spring_security_check");
                dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse());
                FacesContext.getCurrentInstance().responseComplete();
            }

        }
        catch (Exception ex) {
            CommonUtil.addFacesMessage("Login Failed . Bad Credentials", FacesMessage.SEVERITY_ERROR);
        }

        return null;

    }

    public boolean validateLogin() {
        LOGGER.debug("Login initiated....");

        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();

        HttpServletRequest request = (HttpServletRequest) context.getRequest();

        if (validateLoginRequest(request)) {
            return true;
        }
        else {
            return false;
        }
    }

    public void clearSessionContext() {
        LOGGER.debug("Clearing.....SessionContext.....");
        if (SecurityContextHolder.getContext() != null) {
            SecurityContextHolder.createEmptyContext();
            SecurityContextHolder.getContext().setAuthentication(null);
            ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getSession(true);
        }
    }

    private boolean validateLoginRequest(HttpServletRequest request) {
        clearExceptions();
        String userName = request.getParameter("j_username");

        String password = request.getParameter("j_password");

        String company = request.getParameter("loginCompany");

        String site = request.getParameter("loginSite");

        if (userName == null || (userName != null && userName.isEmpty())) {
            CommonUtil.addFacesMessage("Username is mandatory", FacesMessage.SEVERITY_ERROR);
            return false;
        }

        if (password == null || (password != null && password.isEmpty())) {
            CommonUtil.addFacesMessage("Password is mandatory", FacesMessage.SEVERITY_ERROR);
            return false;
        }

        if (serverConfigService.getServerHostingType().equalsIgnoreCase(ServerHostingType.MULTIHOSTING.toString())) {
            if (company == null || (company != null && company.isEmpty())) {
                CommonUtil.addFacesMessage("Company is mandatory", FacesMessage.SEVERITY_ERROR);
                return false;
            }
        }
        if (site == null || (site != null && site.isEmpty())) {
            CommonUtil.addFacesMessage("Site is mandatory", FacesMessage.SEVERITY_ERROR);
            return false;
        }

        return true;
    }
}

0 个答案:

没有答案