HttpSession的是现在空,但不是在要求起动空; 会议无效,所以不要创建一个新的会话(Ht

2019-10-20 21:55发布

之后用户密码被重置用户应该重定向到安全问题页面(/PP/enduser/securityQuestions.do?clear=true'),而不是因为会话无效,并给予用户anonymousUser认证用户越来越AccessDeniedException异常。 我试图从其他类似问题的解决方案的认证对象未在SecurityContext中发现-春3.2.2但解决的办法不是为我工作。

AM使用JDK 7,弹簧安全网络3.1.4.RELEASE,弹簧安全核心3.1.4.RELEASE和Tomcat 7下面是我的身份验证成功处理程序

@Component
@Primary
public class CPAuthenticationSuccessHandler extends DCAuthenticationSuccessHandler {
@Autowired
private CollaborationSecurityService      collabSecurityService;

@Autowired
private AuthenticationFilterConfiguration authenticationConfiguration;

@Autowired
private FailedLoginsLock                  failedLoginsLock;

private static final String               SECURITY_QUESTIONS_URL = "/enduser/securityQuestions.do?clear=true";

private static final Logger               LOGGER                 = Logger.getInstance("dc.auth");

@Override
public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof AuthenticationSuccessEvent)
        try {
            AuthenticationSuccessEvent authenticationSuccessEvent = (AuthenticationSuccessEvent) event;
            SecurityContext ctx = SecurityContextHolder.createEmptyContext();
            SecurityContextHolder.setContext(ctx);
            ctx.setAuthentication(authenticationSuccessEvent.getAuthentication());
         } finally {
            SecurityContextHolder.clearContext();
        }
    super.onApplicationEvent(event);
}

@Override
public void onAuthenticationSuccess(final HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    new DefaultRedirectStrategy().sendRedirect(request, response,
            this.onCPAuthenticationSuccessUrl(request, response, authentication));
}

public String onCPAuthenticationSuccessUrl(final HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    LOGGER.log(Level.INFO, "Successful Authentication Principal--> " + authentication.getPrincipal());
    boolean isNewSession = false;
    Session session = null;

    try {
        if (!sessionHandler.sessionAlreadyBound(sessionFactory)) {
            session = sessionHandler.initiateSession(sessionFactory);
            sessionHandler.beginTransaction(session);
            isNewSession = true;
        }

        if (!SecurityHelper.isCurrentUserAnonymous()
                && collabSecurityService.needSecurityQuestionSetup(authentication.getName()))
            return SECURITY_QUESTIONS_URL;
        else

        return super.onAuthenticationSuccessUrl(request, response, authentication);

    } finally {
        if (isNewSession) {
            sessionHandler.endTransaction(false, sessionFactory);
        }
    }
}

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    super.setApplicationContext(applicationContext);
}

}

安全的applicationContext.xml

<!-- TRUSTED LOGIN CONFIGURATION -->
<http use-expressions="true" auto-config="false" disable-url-rewriting="true" entry-point-ref="http403ForbiddenEntryPoint"
        request-matcher-ref="trustedRequestMatcher">
     <request-cache ref="httpSessionRequestCache"/> 
  <intercept-url pattern="/enduser/**" access="isAuthenticated()" />
  <intercept-url pattern="/index.do" access="isAnonymous()" />
  <custom-filter position="PRE_AUTH_FILTER" ref="trustedAuthenticationFilter" />  
  <http-basic />
  <anonymous />      
  <session-management session-authentication-strategy-ref="customSessionFixationProtectionStrategy" />    
</http> 

<beans:bean id="trustedAuthenticationFilter" class="o.s.s.web.authentication.preauth.RequestHeaderAuthenticationFilter">
   <beans:property name="principalRequestHeader" value="X-Remote-Authenticate"/>
   <beans:property name="authenticationManager" ref="authenticationManager" />
   <beans:property name="exceptionIfHeaderMissing" value="false" />
</beans:bean>   

<beans:bean id="httpSessionRequestCache" class="o.s.s.web.savedrequest.HttpSessionRequestCache"> 
        <beans:property name="createSessionAllowed" value="false" /> 
</beans:bean>

<!-- LOCAL LOGIN CONFIGURATION -->
<http use-expressions="true" auto-config="false" disable-url-rewriting="true" entry-point-ref="loginUrlAuthenticationEntryPoint"
        request-matcher-ref="localAuthRequestMatcher">
  <request-cache ref="httpSessionRequestCache"/> 
  <intercept-url pattern="/admin/**" access="hasRole('ADMIN_PERMISSION')" />
  <intercept-url pattern="/system/**" access="hasRole('ADMIN_PERMISSION')" />
  <intercept-url pattern="/enduser/**" access="isAuthenticated()" />
  <intercept-url pattern="/changePassword.do" access="permitAll"/>      
  <intercept-url pattern="/index.do" access="isAnonymous()" />
  <custom-filter after="SECURITY_CONTEXT_FILTER" ref="welcomePageRedirectFilter" />
  <custom-filter before="LOGOUT_FILTER" ref="internalAuthenticationFilter" />
  <form-login login-page="/index.do" authentication-failure-handler-ref="DCAuthenticationFailureHandler" authentication-success-handler-ref="DCAuthenticationSuccessHandler" />
  <http-basic />
  <anonymous />      
  <session-management session-authentication-strategy-ref="customSessionFixationProtectionStrategy" />  
  <logout success-handler-ref="localLogoutSuccessHandler" />       
</http>
<beans:bean id="exceptionTranslator"
  class="o.s.s.web.access.ExceptionTranslationFilter">
    <beans:constructor-arg><beans:ref bean="loginUrlAuthenticationEntryPoint" /></beans:constructor-arg>    
</beans:bean>   

<beans:bean id="localLogoutSuccessHandler"
  class="com.dc.core.security.authentication.impl.CustomLogoutSuccessHandler">
  <beans:property name="defaultTargetUrl" value="/index.do" />          
</beans:bean>
<!-- SITEMINDER AND SAML LOGIN CONFIGURATION -->   
<http use-expressions="true" auto-config="false" disable-url-rewriting="true" entry-point-ref="http403ForbiddenEntryPoint"
       request-matcher-ref="siteminderSamlAuthRequestMatcher">
<request-cache ref="httpSessionRequestCache"/> 
  <intercept-url pattern="/admin/**" access="hasRole('ADMIN_PERMISSION')" />
  <intercept-url pattern="/system/**" access="hasRole('ADMIN_PERMISSION')" />
  <intercept-url pattern="/enduser/**" access="isAuthenticated()" />
  <intercept-url pattern="/changePassword.do" access="isAuthenticated()"/>      
  <intercept-url pattern="/index.do" access="isAnonymous()" />      
  <custom-filter after="SECURITY_CONTEXT_FILTER" ref="welcomePageRedirectFilter" />
  <custom-filter before="LOGOUT_FILTER" ref="internalAuthenticationFilter" />
  <custom-filter position="PRE_AUTH_FILTER" ref="siteminderSamlFilter" />  
  <http-basic /> 
  <anonymous />         
  <session-management session-authentication-strategy-ref="customSessionFixationProtectionStrategy" />  
  <logout logout-success-url="/index.do" />    
</http>
<beans:bean id="siteminderSamlFilter" class="com.dc.core.security.authentication.impl.RequestHeaderAuthenticationFilter">
 <beans:property name="principalRequestHeader" value="SM_USER"/>
 <beans:property name="authenticationManager" ref="authenticationManager" />
 <beans:property name="exceptionIfHeaderMissing" value="false" />

<!-- As the default value of roleVoter is "ROLE_", overriding the value to empty string -->
<beans:bean id="roleVoter" class="o.s.s.access.vote.RoleVoter">
    <beans:property name="rolePrefix" value="" />
</beans:bean>   

<beans:bean id="loginUrlAuthenticationEntryPoint" 
    class="o.s.s.web.authentication.LoginUrlAuthenticationEntryPoint">
    <beans:constructor-arg type="java.lang.String" value="/index.do"></beans:constructor-arg>       
</beans:bean>

<beans:bean id="http403ForbiddenEntryPoint" 
    class="o.s.s.web.authentication.Http403ForbiddenEntryPoint">        
</beans:bean>

<beans:bean id="saltSource" class="o.s.s.authentication.dao.SystemWideSaltSource">
    <beans:property name="systemWideSalt" value="dcRules!"/>
</beans:bean>

<beans:bean id="passwordEncoder" class="o.s.s.authentication.encoding.ShaPasswordEncoder"/>

<beans:bean id="daoAuthenticationProvider"
    class="o.s.s.authentication.dao.DaoAuthenticationProvider">     
    <beans:property name="saltSource" ref="saltSource"/>
    <beans:property name="passwordEncoder" ref="passwordEncoder"/>
    <beans:property name="userDetailsService" ref="userDetailsService"/>
    <beans:property name="preAuthenticationChecks" ref="DCPreAuthenticationChecks" />
    <beans:property name="postAuthenticationChecks" ref="DCPostAuthenticationChecks" />
</beans:bean>   

<beans:bean id="userInfo" class="com.dc.core.security.model.impl.User" scope="session">
    <aop:scoped-proxy/>
</beans:bean>

<beans:bean id="userDetailsService" class="com.dc.core.security.authentication.impl.DCUserDetailsService">
</beans:bean>

<beans:bean id="securityLoggerListener" class="o.s.s.access.event.LoggerListener"></beans:bean>

<!-- JMX Mbeans:beans configuration -->

<beans:bean id="registry" class="org.springframework.remoting.rmi.RmiRegistryFactoryBean">
    <beans:property name="port" value="${security.jmx.remote.port}" />
</beans:bean>

<beans:bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
    <beans:property name="assembler" ref="assembler" />
    <beans:property name="namingStrategy" ref="namingStrategy" />
    <beans:property name="autodetect" value="true" />
</beans:bean>

<beans:bean id="jmxAttributeSource"
    class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource" />

<beans:bean id="assembler"
    class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">
    <beans:property name="attributeSource" ref="jmxAttributeSource" />
</beans:bean>

<beans:bean id="namingStrategy"
    class="org.springframework.jmx.export.naming.MetadataNamingStrategy">
    <beans:property name="attributeSource" ref="jmxAttributeSource" />
</beans:bean>

<beans:bean id="serverConnector"
    class="org.springframework.jmx.support.ConnectorServerFactoryBean">
    <beans:property name="objectName" value="connector:name=rmi" />
    <beans:property name="serviceUrl"
        value="${security.jmx.remote.url}"  /> 
</beans:bean>

<beans:bean id="clientConnector"
    class="org.springframework.jmx.support.MBeanServerConnectionFactoryBean">
     <beans:property name="serviceUrl"
        value="${security.jmx.remote.url}" /> 
</beans:bean>

我的web.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<context-param>
    <param-name>contextClass</param-name>
    <param-value>
        com.dc.core.spring.CustomXmlWebApplicationContext
    </param-value>
</context-param>

<context-param>
    <param-name>
        javax.servlet.jsp.jstl.fmt.localizationContext
    </param-name>
    <param-value>messages</param-value>
</context-param>

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener
    </listener-class>
</listener>

<listener>
    <listener-class>
        org.springframework.web.context.request.RequestContextListener
    </listener-class>
</listener>

<listener>
    <listener-class>
        com.dc.core.security.listener.SessionListener
    </listener-class>
</listener>

之后,用户会被重定向到/enduser/securityQuestions.do页面的用户越来越customaccessdenied例外,踢中后卫到登录页面(index.do)

2014-09-09 22:41:09,204 DEBUG | o.s.s.web.context.SecurityContextPersistenceFilter |  | 91U89hqS96LB | SecurityContextHolder now cleared, as request processing completed
2014-09-09 22:41:14,727 DEBUG | o.s.s.w.FilterChainProxy |  | kfHMkpzvUJYw | /j_spring_security_check at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2014-09-09 22:41:14,728 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository |  | kfHMkpzvUJYw | HttpSession returned null object for SPRING_SECURITY_CONTEXT
2014-09-09 22:41:14,729 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository |  | kfHMkpzvUJYw | No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@61763e58. A new one will be created.
2014-09-09 22:41:14,730 DEBUG | o.s.s.w.FilterChainProxy |  | kfHMkpzvUJYw | /j_spring_security_check at position 2 of 12 in additional filter chain; firing Filter: 'WelcomePageRedirectFilter'
2014-09-09 22:41:14,731 DEBUG | o.s.s.w.FilterChainProxy |  | kfHMkpzvUJYw | /j_spring_security_check at position 3 of 12 in additional filter chain; firing Filter: 'InternalAuthenticationFilter'
2014-09-09 22:41:14,732 DEBUG | o.s.s.w.FilterChainProxy |  | kfHMkpzvUJYw | /j_spring_security_check at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2014-09-09 22:41:14,733 DEBUG | o.s.s.w.FilterChainProxy |  | kfHMkpzvUJYw | /j_spring_security_check at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2014-09-09 22:41:14,734 DEBUG | o.s.s.w.authentication.UsernamePasswordAuthenticationFilter |  | kfHMkpzvUJYw | Request is to process authentication
2014-09-09 22:41:14,734 DEBUG | o.s.s.authentication.ProviderManager |  | kfHMkpzvUJYw | Authentication attempt using com.dc.apps.collaborationportal.security.service.CPDaoAuthenticationProvider
2014-09-09 22:41:14,745 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /j_spring_security_check at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2014-09-09 22:41:14,747 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository |  | 91U89hqS96LB | HttpSession returned null object for SPRING_SECURITY_CONTEXT
2014-09-09 22:41:14,747 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository |  | 91U89hqS96LB | No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@61763e58. A new one will be created.
2014-09-09 22:41:14,748 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /j_spring_security_check at position 2 of 12 in additional filter chain; firing Filter: 'WelcomePageRedirectFilter'
2014-09-09 22:41:14,748 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /j_spring_security_check at position 3 of 12 in additional filter chain; firing Filter: 'InternalAuthenticationFilter'
2014-09-09 22:41:14,749 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /j_spring_security_check at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2014-09-09 22:41:14,750 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /j_spring_security_check at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2014-09-09 22:41:14,750 DEBUG | o.s.s.w.authentication.UsernamePasswordAuthenticationFilter |  | 91U89hqS96LB | Request is to process authentication
2014-09-09 22:41:14,751 DEBUG | o.s.s.authentication.ProviderManager |  | 91U89hqS96LB | Authentication attempt using com.dc.apps.collaborationportal.security.service.CPDaoAuthenticationProvider
2014-09-09 22:41:14,792 DEBUG | o.s.s.w.authentication.UsernamePasswordAuthenticationFilter |  | 91U89hqS96LB | Authentication success. Updating SecurityContextHolder to contain: o.s.s.authentication.UsernamePasswordAuthenticationToken@86969601: Principal: o.s.s.core.userdetails.User@49520377: Username: test1@dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails@fffe9938:  SessionId: 0F7B56BA141C0A001C95180FE06BE864; Not granted any authorities
2014-09-09 22:41:14,798 DEBUG | o.s.s.w.authentication.UsernamePasswordAuthenticationFilter |  | kfHMkpzvUJYw | Authentication success. Updating SecurityContextHolder to contain: o.s.s.authentication.UsernamePasswordAuthenticationToken@86969601: Principal: o.s.s.core.userdetails.User@49520377: Username: test1@dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails@fffe9938:  SessionId: 0F7B56BA141C0A001C95180FE06BE864; Not granted any authorities
2014-09-09 22:41:14,870 DEBUG | o.s.s.w.DefaultRedirectStrategy | test1@dc.com | 91U89hqS96LB | Redirecting to '/PP/enduser/securityQuestions.do?clear=true'
2014-09-09 22:41:14,870 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository | test1@dc.com | 91U89hqS96LB | HttpSession is now null, but was not null at start of request; session was invalidated, so do not create a new session
2014-09-09 22:41:14,870 DEBUG | o.s.s.w.context.SecurityContextPersistenceFilter |  | 91U89hqS96LB | SecurityContextHolder now cleared, as request processing completed
2014-09-09 22:41:14,898 DEBUG | o.s.s.w.DefaultRedirectStrategy | test1@dc.com | kfHMkpzvUJYw | Redirecting to '/PP/enduser/securityQuestions.do?clear=true'
2014-09-09 22:41:14,899 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository | test1@dc.com | kfHMkpzvUJYw | SecurityContext stored to HttpSession: 'o.s.s.core.context.SecurityContextImpl@86969601: Authentication: o.s.s.authentication.UsernamePasswordAuthenticationToken@86969601: Principal: o.s.s.core.userdetails.User@49520377: Username: test1@dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails@fffe9938:  SessionId: 0F7B56BA141C0A001C95180FE06BE864; Not granted any authorities'
2014-09-09 22:41:14,899 DEBUG | o.s.s.w.context.SecurityContextPersistenceFilter |  | kfHMkpzvUJYw | SecurityContextHolder now cleared, as request processing completed
2014-09-09 22:41:15,880 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2014-09-09 22:41:15,881 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository |  | 91U89hqS96LB | No HttpSession currently exists
2014-09-09 22:41:15,881 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository |  | 91U89hqS96LB | No SecurityContext was available from the HttpSession: null. A new one will be created.
2014-09-09 22:41:15,882 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 2 of 12 in additional filter chain; firing Filter: 'WelcomePageRedirectFilter'
2014-09-09 22:41:15,884 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 3 of 12 in additional filter chain; firing Filter: 'InternalAuthenticationFilter'
2014-09-09 22:41:15,884 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2014-09-09 22:41:15,885 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2014-09-09 22:41:15,885 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 6 of 12 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2014-09-09 22:41:15,886 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2014-09-09 22:41:15,886 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2014-09-09 22:41:15,887 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2014-09-09 22:41:15,888 DEBUG | o.s.s.w.authentication.AnonymousAuthenticationFilter | anonymousUser | 91U89hqS96LB | Populated SecurityContextHolder with anonymous token: 'o.s.s.authentication.AnonymousAuthenticationToken@6faab5ec: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails@ffffc434:  SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
2014-09-09 22:41:15,888 DEBUG | o.s.s.w.FilterChainProxy | anonymousUser | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2014-09-09 22:41:15,889 DEBUG | o.s.s.w.session.SessionManagementFilter | anonymousUser | 91U89hqS96LB | Requested session ID 0F7B56BA141C0A001C95180FE06BE864 is invalid.
2014-09-09 22:41:15,889 DEBUG | o.s.s.w.FilterChainProxy | anonymousUser | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2014-09-09 22:41:15,890 DEBUG | o.s.s.w.FilterChainProxy | anonymousUser | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2014-09-09 22:41:15,891 DEBUG | o.s.s.w.util.AntPathRequestMatcher | anonymousUser | 91U89hqS96LB | Checking match of request : '/enduser/securityquestions.do'; against '/admin/**'
2014-09-09 22:41:15,891 DEBUG | o.s.s.w.util.AntPathRequestMatcher | anonymousUser | 91U89hqS96LB | Checking match of request : '/enduser/securityquestions.do'; against '/system/**'
2014-09-09 22:41:15,892 DEBUG | o.s.s.w.util.AntPathRequestMatcher | anonymousUser | 91U89hqS96LB | Checking match of request : '/enduser/securityquestions.do'; against '/enduser/**'
2014-09-09 22:41:15,893 DEBUG | o.s.s.w.access.intercept.FilterSecurityInterceptor | anonymousUser | 91U89hqS96LB | Secure object: FilterInvocation: URL: /enduser/securityQuestions.do?clear=true; Attributes: [isAuthenticated()]
2014-09-09 22:41:15,893 DEBUG | o.s.s.w.access.intercept.FilterSecurityInterceptor | anonymousUser | 91U89hqS96LB | Previously Authenticated: o.s.s.authentication.AnonymousAuthenticationToken@6faab5ec: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails@ffffc434:  SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2014-09-09 22:41:15,894 DEBUG | o.s.s.access.vote.AffirmativeBased | anonymousUser | 91U89hqS96LB | Voter: o.s.s.w.access.expression.WebExpressionVoter@1fb01f38, returned: -1
2014-09-09 22:41:15,895 WARN  | o.s.s.access.event.LoggerListener | anonymousUser | 91U89hqS96LB | Security authorization failed due to: o.s.s.access.AccessDeniedException: Access is denied; authenticated principal: o.s.s.authentication.AnonymousAuthenticationToken@6faab5ec: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails@ffffc434:  SessionId: null; Granted Authorities: ROLE_ANONYMOUS; secure object: FilterInvocation: URL: /enduser/securityQuestions.do?clear=true; configuration attributes: [isAuthenticated()]
2014-09-09 22:41:15,896 DEBUG | o.s.s.w.access.ExceptionTranslationFilter | anonymousUser | 91U89hqS96LB | Access is denied (user is anonymous); redirecting to authentication entry point
o.s.s.access.AccessDeniedException: Access is denied
at o.s.s.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83)

经过不断尝试了几分钟用户被重定向到securityQuestion页及以下是从index.do到securityquestions.do成功重定向日志

2014-09-09 22:29:32,006 DEBUG | o.s.s.w.FilterChainProxy |  | cPZ5kp4XKw3e | /j_spring_security_check at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2014-09-09 22:29:32,007 DEBUG | o.s.s.w.authentication.UsernamePasswordAuthenticationFilter |  | cPZ5kp4XKw3e | Request is to process authentication
2014-09-09 22:29:32,007 DEBUG | o.s.s.authentication.ProviderManager |  | cPZ5kp4XKw3e | Authentication attempt using com.dc.apps.collaborationportal.security.service.CPDaoAuthenticationProvider
2014-09-09 22:29:32,078 DEBUG | o.s.s.w.authentication.UsernamePasswordAuthenticationFilter |  | cPZ5kp4XKw3e | Authentication success. Updating SecurityContextHolder to contain: o.s.s.authentication.UsernamePasswordAuthenticationToken@79692524: Principal: o.s.s.core.userdetails.User@49520377: Username: test1@dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails@12afc:  SessionId: 8822A6A448B6B75C997DF69C9B474DE6; Not granted any authorities
2014-09-09 22:29:32,296 DEBUG | o.s.s.w.DefaultRedirectStrategy | test1@dc.com | cPZ5kp4XKw3e | Redirecting to '/PP/enduser/securityQuestions.do?clear=true'
2014-09-09 22:29:32,297 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository | test1@dc.com | cPZ5kp4XKw3e | SecurityContext stored to HttpSession: 'o.s.s.core.context.SecurityContextImpl@79692524: Authentication: o.s.s.authentication.UsernamePasswordAuthenticationToken@79692524: Principal: o.s.s.core.userdetails.User@49520377: Username: test1@dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails@12afc:  SessionId: 8822A6A448B6B75C997DF69C9B474DE6; Not granted any authorities'
2014-09-09 22:29:32,298 DEBUG | o.s.s.w.context.SecurityContextPersistenceFilter |  | cPZ5kp4XKw3e | SecurityContextHolder now cleared, as request processing completed
2014-09-09 22:29:33,309 DEBUG | o.s.s.w.FilterChainProxy |  | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2014-09-09 22:29:33,309 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository |  | 91U89hqS96LB | Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'o.s.s.core.context.SecurityContextImpl@79692524: Authentication: o.s.s.authentication.UsernamePasswordAuthenticationToken@79692524: Principal: o.s.s.core.userdetails.User@49520377: Username: test1@dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails@12afc:  SessionId: 8822A6A448B6B75C997DF69C9B474DE6; Not granted any authorities'
2014-09-09 22:29:33,310 DEBUG | o.s.s.w.FilterChainProxy | test1@dc.com | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 2 of 12 in additional filter chain; firing Filter: 'WelcomePageRedirectFilter'

Answer 1:

创建一个新的过滤器下面将覆盖默认的Tomcat JSESSIONID行为

public class HttpsCookieFilter implements Filter {
private static final Logger LOGGER = Logger.getInstance(HttpsCookieFilter.class);

@Override
public void destroy() {
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws  IOException,
         ServletException {

    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final HttpServletResponse httpResponse = (HttpServletResponse) response;
    final HttpSession session = httpRequest.getSession(false);

    if (session != null) {
        final Cookie sessionCookie = new Cookie("JSESSIONID", session.getId());
        sessionCookie.setMaxAge(readCookieTimeoutfromProperties());
        sessionCookie.setSecure(false);
        sessionCookie.setPath(httpRequest.getContextPath());
        httpResponse.addCookie(sessionCookie);
        LOGGER.log(Level.DEBUG, "Session not null and setting SessionCookie --> " + sessionCookie.getValue()
                + "; SessionCookie Age --> " + sessionCookie.getMaxAge());
    }

    chain.doFilter(request, response);
}

@Override
public void init(FilterConfig arg0) throws ServletException {
}

private int readCookieTimeoutfromProperties() {
    ResourceBundleMessageSource bean = new ResourceBundleMessageSource();
    bean.setBasename("application-messages");
    String tmeout = bean.getMessage("security.cookie.timeout", null, Locale.getDefault());
    return Integer.parseInt(tmeout);
}

}

和调用之前springSecurityFilterChain在web.xml此过滤器<



文章来源: HttpSession is now null, but was not null at start of request; session was invalidated, so do not create a new session