Results 1 to 2 of 2

Thread: Need to display different error page for timeout and unathourized url access

  1. #1
    Join Date
    Mar 2010
    Posts
    22

    Default Need to display different error page for timeout and unathourized url access

    hi experts,

    My spring security is using custom filters to 3 different applications, with different login,logout and error pages. For one application, I need to show a different message for timeout and different message when user tries to access a secure url. I need this function for uri's /rest/ccss/student/** and ROLE_CCSS_STUDENT role.

    Version of spring being used: 3.1

    Code:
    spring.security.xml
    ..........		
    			 <filter-chain pattern="/rest/ccss/student/**"
    				filters="ccssConcurrentSessionFilter,httpSessionContextIntegrationFilter,
    				ccssLogoutFilter,ccssAuthenticationProcessingFilter,
    				sessionAware,basicProcessingFilter,anonymousProcessingFilter,ccssExceptionTranslationFilter,filterSecurityInterceptor" />		
    			
    			<filter-chain pattern="/ccss/**"
    				filters="ccssConcurrentSessionFilter,httpSessionContextIntegrationFilter,
    				ccssLogoutFilter,ccssAuthenticationProcessingFilter,
    				sessionAware,basicProcessingFilter,anonymousProcessingFilter,ccssExceptionTranslationFilter,filterSecurityInterceptor" />	
    			<!-- retaining the same filter chain as smarttrack for k thru 12 -->
    		</filter-chain-map>
    	</beans:bean>
    	<beans:bean id="concurrentSessionFilter"
    		class="org.springframework.security.concurrent.ConcurrentSessionFilter">
    		<!-- beans:property name="maximumSessions" value="1" /-->
    		<beans:property name="expiredUrl" value="/login.spr?login_error=2" />
    		<beans:property name="sessionRegistry">
    			<beans:ref local="sessionRegistry" />
    		</beans:property>
    	</beans:bean>	
    	<beans:bean id="ccssConcurrentSessionFilter"
    		class="org.springframework.security.concurrent.ConcurrentSessionFilter">
    		<!-- beans:property name="maximumSessions" value="1" /-->
    		<beans:property name="expiredUrl" value="/login-ccss.spr?login_error=1" />
    		<beans:property name="sessionRegistry">
    			<beans:ref local="sessionRegistry" />
    		</beans:property>
    	</beans:bean>
    	
    	<beans:bean id="sessionRegistry"
    		class="org.springframework.security.concurrent.SessionRegistryImpl" />
    	<beans:bean id="httpSessionContextIntegrationFilter"
    		class="org.springframework.security.context.HttpSessionContextIntegrationFilter">
    		<beans:property name="allowSessionCreation" value="true" />
    	</beans:bean>
    	<!--end of httpSessionContextIntegrationFilter -->
    
    
    	   
    	<beans:bean id="ccssLogoutFilter"
    		class="abc.scorelms.security.support.LogoutSessionTimeOutFilter">
    		<custom-filter position="LOGOUT_FILTER" />
    		<beans:constructor-arg value="/login-ccss.spr?logout=Yes" /> 
    		<beans:constructor-arg value="/login-ccss.spr?timeout=Yes" /> 
    		<beans:constructor-arg>
    			<beans:list>
    				<beans:bean
    					class="org.springframework.security.ui.logout.SecurityContextLogoutHandler" />
    			</beans:list>
    		</beans:constructor-arg>
    		<beans:property name="filterProcessesUrl" value="/ccss/j_spring_security_logout" />
    	</beans:bean>
    	<beans:bean id="preAuthenticationProcessingFilter"
    		class="abc.scorelms.security.support.SSOPreAuthenticatedProcessingFilter">
    		<custom-filter position="PRE_AUTH_FILTER" />
    		<beans:property name="authenticationManager" ref="_authenticationManager" />
    	</beans:bean>
    
        <authentication-manager alias="_authenticationManager"/>
    	<beans:bean id="daoAuthenticationProvider"
    		class="org.springframework.security.providers.dao.DaoAuthenticationProvider">
            <custom-authentication-provider />
    		<!-- removed custom authentication provider, since http is not used-->
    		<beans:property name="userDetailsService" ref="userDetailsService" />
    		<beans:property name="passwordEncoder" ref="passwordEncoder" />
    		<beans:property name="userCache" ref="userCache" />
    	</beans:bean>
    
    	
    	<beans:bean id="passwordEncoder"
    		class="org.springframework.security.providers.encoding.ShaPasswordEncoder" />
    
    	<beans:bean id="userDetailsService"
    		class="abc.scorelms.security.service.impl.UserDetailsServiceImpl" />
    	<beans:bean id="passwordEncryptor"
    		class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor">
    		<beans:property name="password" value="${lms.encryption.password}" />
    	</beans:bean>
    	<beans:bean id="authenticationProcessingFilter"
    		class="abc.scorelms.security.support.PCSTaffAwareAuthenticationProcessingFilter">
    		<beans:property name="authenticationManager" ref="_authenticationManager" />
    		<beans:property name="authenticationFailureUrl" value="/login.spr?login_error=1" />
    		<beans:property name="defaultTargetUrl" value="/login.spr" />
    		<beans:property name="filterProcessesUrl" value="/j_spring_security_check" />
    	</beans:bean>
    	
    	<beans:bean id="ccssAuthenticationProcessingFilter"
    		class="org.springframework.security.ui.webapp.AuthenticationProcessingFilter">
    		<beans:property name="authenticationManager" ref="_authenticationManager" />
    		<beans:property name="authenticationFailureUrl" value="/login-ccss.spr?login_error=1" />
    		<beans:property name="defaultTargetUrl" value="/login-ccss.spr" />
    		<beans:property name="filterProcessesUrl" value="/ccss/j_spring_security_check" />
    	</beans:bean>
    	<beans:bean id="sessionAware"
    		class="abc.scorelms.security.support.SessionAwareAuthenticationProcessingFilter">
    	</beans:bean>
    	<!-- end of custom session aware filter-->
    
    	<!-- Basic authentication -->
    
    	<beans:bean id="basicProcessingFilter"
    		class="org.springframework.security.ui.basicauth.BasicProcessingFilter">
    		<beans:property name="authenticationManager">
    			<beans:ref bean="_authenticationManager" />
    		</beans:property>
    		<beans:property name="authenticationEntryPoint">
    			<beans:ref bean="authenticationEntryPoint" />
    		</beans:property>
    	</beans:bean>
    	<!-- end of basic authentication-->
    
    	<beans:bean id="epBasicProcessingFilter"
    		class="org.springframework.security.ui.basicauth.BasicProcessingFilter">
    		<beans:property name="authenticationManager">
    			<beans:ref bean="_authenticationManager" />
    		</beans:property>
    		<beans:property name="authenticationEntryPoint">
    			<beans:ref bean="epAuthenticationEntryPoint" />
    		</beans:property>
    	</beans:bean>
    	
    	<!--
    		TODO: implementation of
    		org.springframework.security.wrapper.SecurityContextHolderAwareRequestFilter
    	-->
    
    
    	<!--TODO: remember me service-->
    
    
    	<!-- Anonymous -->
    	<beans:bean id="anonymousProcessingFilter"
    		class="org.springframework.security.providers.anonymous.AnonymousProcessingFilter">
    		<beans:property name="key">
    			<beans:value>app1</beans:value>
    		</beans:property>
    		<beans:property name="userAttribute">
    			<beans:value>anonymousUser,ROLE_ANONYMOUS
    			</beans:value>
    		</beans:property>
    	</beans:bean>
    	<beans:bean id="anonymousAuthenticationProvider"
    		class="org.springframework.security.providers.anonymous.AnonymousAuthenticationProvider">
    		<beans:property name="key">
    			<beans:value>app1</beans:value>
    		</beans:property>
    	</beans:bean>
    
    	<!--
    		using filter security interceptor instead of AnonymousProcessingFilter
    	-->
    	<beans:bean id="filterSecurityInterceptor"
    		class="org.springframework.security.intercept.web.FilterSecurityInterceptor">
    		<beans:property name="objectDefinitionSource">
    			<filter-invocation-definition-source
    				path-type="ant">
    				<intercept-url pattern="/login-ccss.spr" access="IS_AUTHENTICATED_ANONYMOUSLY" />				
    				
    				<intercept-url pattern="/student/ccss/**"
    					access="ROLE_CCSS_STUDENT" />
    					<intercept-url pattern="/rest/ccss/**"
    					access="ROLE_CCSS_STUDENT" />
    										
    			</filter-invocation-definition-source>
    		</beans:property>
    		<beans:property name="authenticationManager" ref="_authenticationManager" />
    		<beans:property name="accessDecisionManager" ref="accessDecisionManager" />
    	</beans:bean>
    
    	<beans:bean id="accessDecisionManager"
    		class="org.springframework.security.vote.AffirmativeBased">
    		<beans:property name="decisionVoters">
    			<beans:list>
    				<beans:bean class="org.springframework.security.vote.RoleVoter" />
    				<beans:bean class="org.springframework.security.vote.AuthenticatedVoter" />
    			</beans:list>
    		</beans:property>
    	</beans:bean>
    	<beans:bean id="exceptionTranslationFilter"
    		class="org.springframework.security.ui.ExceptionTranslationFilter">
    		<beans:property name="authenticationEntryPoint" ref="authenticationEntryPoint" />
    	</beans:bean>
    	<beans:bean id="authenticationEntryPoint"
    		class="abc.scorelms.security.support.AjaxAwareAuthenticationEntryPoint">
    		<beans:property name="loginFormUrl">
    			<beans:value>/login.spr</beans:value>
    		</beans:property>
    		<beans:property name="forceHttps">
    			<beans:value>false</beans:value>
    		</beans:property>
    	</beans:bean>
    	
    	<beans:bean id="ccssExceptionTranslationFilter"
    		class="org.springframework.security.ui.ExceptionTranslationFilter">
    		<beans:property name="authenticationEntryPoint" ref="ccssAuthenticationEntryPoint" />
    	</beans:bean>
    	<beans:bean id="ccssAuthenticationEntryPoint"
    		class="abc.scorelms.security.support.AjaxAwareAuthenticationEntryPoint">
    		<beans:property name="loginFormUrl">
    			<beans:value>/login-ccss.spr</beans:value>
    		</beans:property>
    		<beans:property name="forceHttps">
    			<beans:value>false</beans:value>
    		</beans:property>
    	</beans:bean>
    	
    </beans:beans>
    Totally object oriented

  2. #2
    Join Date
    Mar 2010
    Posts
    22

    Default

    <code>
    package abc.scorelms.security.support;

    import java.io.IOException;

    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.springframework.security.Authentication;
    import org.springframework.security.context.SecurityConte xtHolder;
    import org.springframework.security.ui.FilterChainOrder;
    import org.springframework.security.ui.SpringSecurityFilt er;
    import org.springframework.security.ui.logout.LogoutHandl er;
    import org.springframework.security.util.RedirectUtils;
    import org.springframework.security.util.UrlUtils;
    import org.springframework.util.Assert;
    import org.springframework.util.StringUtils;

    public class LogoutSessionTimeOutFilter extends SpringSecurityFilter {

    //~ Instance fields ================================================== ==============================================

    private String filterProcessesUrl = "/j_spring_security_logout";
    private String logoutSuccessUrl;
    private String sessionTimeOutUrl;
    private LogoutHandler[] handlers;
    private boolean useRelativeContext;

    //~ Constructors ================================================== =================================================

    public LogoutSessionTimeOutFilter(String logoutSuccessUrl, String sessionTimeOutUrl, LogoutHandler[] handlers) {
    Assert.notEmpty(handlers, "LogoutHandlers are required");
    this.logoutSuccessUrl = logoutSuccessUrl;
    this.sessionTimeOutUrl = sessionTimeOutUrl;
    Assert.isTrue(UrlUtils.isValidRedirectUrl(logoutSu ccessUrl), logoutSuccessUrl + " isn't a valid redirect URL");
    this.handlers = handlers;
    }

    //~ Methods ================================================== ================================================== ====

    public void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException,
    ServletException {

    if (requiresLogout(request, response)) {
    Authentication auth = SecurityContextHolder.getContext().getAuthenticati on();

    if (logger.isDebugEnabled()) {
    logger.debug("Logging out user '" + auth + "' and redirecting to logout page");
    }

    for (int i = 0; i < handlers.length; i++) {
    handlers[i].logout(request, response, auth);
    }

    String targetUrl = determineTargetUrl(request, response);

    if(auth == null){
    //session timedout
    targetUrl = getSessionTimeOutUrl();
    }

    sendRedirect(request, response, targetUrl);

    return;
    }

    chain.doFilter(request, response);
    }

    /**
    * Allow subclasses to modify when a logout should take place.
    *
    * @param request the request
    * @param response the response
    *
    * @return <code>true</code> if logout should occur, <code>false</code> otherwise
    */
    protected boolean requiresLogout(HttpServletRequest request, HttpServletResponse response) {
    String uri = request.getRequestURI();
    int pathParamIndex = uri.indexOf(';');

    if (pathParamIndex > 0) {
    // strip everything from the first semi-colon
    uri = uri.substring(0, pathParamIndex);
    }

    int queryParamIndex = uri.indexOf('?');

    if (queryParamIndex > 0) {
    // strip everything from the first question mark
    uri = uri.substring(0, queryParamIndex);
    }

    if ("".equals(request.getContextPath())) {
    return uri.endsWith(filterProcessesUrl);
    }

    return uri.endsWith(request.getContextPath() + filterProcessesUrl);
    }

    /**
    * Returns the target URL to redirect to after logout.
    * <p>
    * By default it will check for a <tt>logoutSuccessUrl</tt> parameter in
    * the request and use this. If that isn't present it will use the configured <tt>logoutSuccessUrl</tt>. If this
    * hasn't been set it will check the Referer header and use the URL from there.
    *
    */
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
    String targetUrl = request.getParameter("logoutSuccessUrl");

    if(!StringUtils.hasLength(targetUrl)) {
    targetUrl = getLogoutSuccessUrl();
    }

    if (!StringUtils.hasLength(targetUrl)) {
    targetUrl = request.getHeader("Referer");
    }

    if (!StringUtils.hasLength(targetUrl)) {
    targetUrl = "/";
    }

    return targetUrl;
    }

    /**
    * Allow subclasses to modify the redirection message.
    *
    * @param request the request
    * @param response the response
    * @param url the URL to redirect to
    *
    * @throws IOException in the event of any failure
    */
    protected void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
    throws IOException {

    RedirectUtils.sendRedirect(request, response, url, useRelativeContext);
    }

    public void setFilterProcessesUrl(String filterProcessesUrl) {
    Assert.hasText(filterProcessesUrl, "FilterProcessesUrl required");
    Assert.isTrue(UrlUtils.isValidRedirectUrl(filterPr ocessesUrl), filterProcessesUrl + " isn't a valid redirect URL");
    this.filterProcessesUrl = filterProcessesUrl;
    }

    protected String getLogoutSuccessUrl() {
    return logoutSuccessUrl;
    }

    protected String getFilterProcessesUrl() {
    return filterProcessesUrl;
    }

    public void setUseRelativeContext(boolean useRelativeContext) {
    this.useRelativeContext = useRelativeContext;
    }


    public String getSessionTimeOutUrl() {
    return sessionTimeOutUrl;
    }

    public void setSessionTimeOutUrl(String sessionTimeOutUrl) {
    this.sessionTimeOutUrl = sessionTimeOutUrl;
    }

    public int getOrder() {
    return FilterChainOrder.LOGOUT_FILTER;
    }
    }

    <code>
    Totally object oriented

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •