Merge pull request #64 from mmoayyed/CAS-219

CAS-219: Provide support for certain urls to be excluded from CAS filters
This commit is contained in:
Misagh Moayyed 2014-03-17 00:21:53 -07:00
commit f018f54c4c
11 changed files with 375 additions and 22 deletions

View File

@ -19,10 +19,14 @@
package org.jasig.cas.client.authentication;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.util.ReflectUtils;
@ -42,11 +46,10 @@ import org.jasig.cas.client.validation.Assertion;
* <p>Please see AbstractCasFilter for additional properties.</p>
*
* @author Scott Battaglia
* @version $Revision: 11768 $ $Date: 2007-02-07 15:44:16 -0500 (Wed, 07 Feb 2007) $
* @author Misagh Moayyed
* @since 3.0
*/
public class AuthenticationFilter extends AbstractCasFilter {
/**
* The URL to the CAS Server login.
*/
@ -65,7 +68,18 @@ public class AuthenticationFilter extends AbstractCasFilter {
private GatewayResolver gatewayStorage = new DefaultGatewayResolverImpl();
private AuthenticationRedirectStrategy authenticationRedirectStrategy = new DefaultAuthenticationRedirectStrategy();
private UrlPatternMatcherStrategy ignoreUrlPatternMatcherStrategyClass = null;
private static final Map<String, Class<? extends UrlPatternMatcherStrategy>> PATTERN_MATCHER_TYPES =
new HashMap<String, Class<? extends UrlPatternMatcherStrategy>>();
static {
PATTERN_MATCHER_TYPES.put("CONTAINS", ContainsPatternUrlPatternMatcherStrategy.class);
PATTERN_MATCHER_TYPES.put("REGEX", RegexUrlPatternMatcherStrategy.class);
PATTERN_MATCHER_TYPES.put("EXACT", ExactUrlPatternMatcherStrategy.class);
}
protected void initInternal(final FilterConfig filterConfig) throws ServletException {
if (!isIgnoreInitConfiguration()) {
super.initInternal(filterConfig);
@ -75,13 +89,36 @@ public class AuthenticationFilter extends AbstractCasFilter {
logger.trace("Loaded renew parameter: {}", this.renew);
setGateway(parseBoolean(getPropertyFromInitParams(filterConfig, "gateway", "false")));
logger.trace("Loaded gateway parameter: {}", this.gateway);
final String ignorePattern = getPropertyFromInitParams(filterConfig, "ignorePattern", null);
logger.trace("Loaded ignorePattern parameter: {}", ignorePattern);
final String ignoreUrlPatternType = getPropertyFromInitParams(filterConfig, "ignoreUrlPatternType", "REGEX");
logger.trace("Loaded ignoreUrlPatternType parameter: {}", ignoreUrlPatternType);
if (ignorePattern != null) {
final Class<? extends UrlPatternMatcherStrategy> ignoreUrlMatcherClass = PATTERN_MATCHER_TYPES.get(ignoreUrlPatternType);
if (ignoreUrlMatcherClass != null) {
this.ignoreUrlPatternMatcherStrategyClass = ReflectUtils.newInstance(ignoreUrlMatcherClass.getName());
} else {
try {
logger.trace("Assuming {} is a qualified class name...", ignoreUrlPatternType);
this.ignoreUrlPatternMatcherStrategyClass = ReflectUtils.newInstance(ignoreUrlPatternType);
} catch (final IllegalArgumentException e) {
logger.error("Could not instantiate class [{}]", ignoreUrlPatternType, e);
}
}
if (this.ignoreUrlPatternMatcherStrategyClass != null) {
this.ignoreUrlPatternMatcherStrategyClass.setPattern(ignorePattern);
}
}
final String gatewayStorageClass = getPropertyFromInitParams(filterConfig, "gatewayStorageClass", null);
if (gatewayStorageClass != null) {
this.gatewayStorage = ReflectUtils.newInstance(gatewayStorageClass);
}
final String authenticationRedirectStrategyClass = getPropertyFromInitParams(filterConfig,
"authenticationRedirectStrategyClass", null);
@ -98,8 +135,16 @@ public class AuthenticationFilter extends AbstractCasFilter {
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
final FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpServletResponse response = (HttpServletResponse) servletResponse;
if (isRequestUrlExcluded(request)) {
logger.debug("Request is ignored.");
filterChain.doFilter(request, response);
return;
}
final HttpSession session = request.getSession(false);
final Assertion assertion = session != null ? (Assertion) session.getAttribute(CONST_CAS_ASSERTION) : null;
@ -151,4 +196,17 @@ public class AuthenticationFilter extends AbstractCasFilter {
public final void setGatewayStorage(final GatewayResolver gatewayStorage) {
this.gatewayStorage = gatewayStorage;
}
private boolean isRequestUrlExcluded(final HttpServletRequest request) {
if (this.ignoreUrlPatternMatcherStrategyClass == null) {
return false;
}
final StringBuffer urlBuffer = request.getRequestURL();
if (request.getQueryString() != null) {
urlBuffer.append("?").append(request.getQueryString());
}
final String requestUri = urlBuffer.toString();
return this.ignoreUrlPatternMatcherStrategyClass.matches(requestUri);
}
}

View File

@ -0,0 +1,38 @@
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.client.authentication;
/**
* A pattern matcher that looks inside the url to find the exact pattern specified.
*
* @author Misagh Moayyed
* @since 3.3.1
*/
public final class ContainsPatternUrlPatternMatcherStrategy implements UrlPatternMatcherStrategy {
private String pattern;
public boolean matches(final String url) {
return url.contains(this.pattern);
}
public void setPattern(final String pattern) {
this.pattern = pattern;
}
}

View File

@ -0,0 +1,22 @@
package org.jasig.cas.client.authentication;
/**
* A pattern matcher that produces a successful match if the pattern
* specified matches the given url exactly and equally.
*
* @author Misagh Moayyed
* @since 3.3.1
*/
public final class ExactUrlPatternMatcherStrategy implements UrlPatternMatcherStrategy {
private String pattern;
public boolean matches(final String url) {
return url.equals(this.pattern);
}
public void setPattern(final String pattern) {
this.pattern = pattern;
}
}

View File

@ -0,0 +1,41 @@
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.client.authentication;
import java.util.regex.Pattern;
/**
* A pattern matcher that looks inside the url to find the pattern,. that
* is assumed to have been specified via regular expressions syntax.
*
* @author Misagh Moayyed
* @since 3.3.1
*/
public final class RegexUrlPatternMatcherStrategy implements UrlPatternMatcherStrategy {
private Pattern pattern;
public boolean matches(final String url) {
return this.pattern.matcher(url).find();
}
public void setPattern(final String pattern) {
this.pattern = Pattern.compile(pattern);
}
}

View File

@ -0,0 +1,42 @@
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.client.authentication;
/**
* Defines an abstraction by which request urls can be matches against a given pattern.
* New instances for all extensions for this strategy interface will be created per
* each request. The client will ultimately invoke the {@link #matches(String)} method
* having already applied and set the pattern via the {@link #setPattern(String)} method.
* The pattern itself will be retrieved via the client configuration.
* @author Misagh Moayyed
* @since 3.3.1
*/
public interface UrlPatternMatcherStrategy {
/**
* Execute the match between the given pattern and the url
* @param url the request url typically with query strings included
* @return true if match is successful
*/
boolean matches(String url);
/**
* The pattern against which the url is compared
* @param pattern
*/
void setPattern(String pattern);
}

View File

@ -34,11 +34,11 @@ import javax.servlet.http.HttpServletResponse;
* <p>Please note that one of the two above parameters must be set.</p>
*
* @author Scott Battaglia
* @version $Revision$ $Date$
* @author Misagh Moayyed
* @since 3.1
*/
public abstract class AbstractCasFilter extends AbstractConfigurationFilter {
/** Represents the constant for where the assertion will be located in memory. */
public static final String CONST_CAS_ASSERTION = "_const_cas_assertion_";
@ -47,7 +47,7 @@ public abstract class AbstractCasFilter extends AbstractConfigurationFilter {
/** Defines the parameter to look for for the service. */
private String serviceParameterName = "service";
/** Sets where response.encodeUrl should be called on service urls when constructed. */
private boolean encodeServiceUrl = true;
@ -71,12 +71,13 @@ public abstract class AbstractCasFilter extends AbstractConfigurationFilter {
logger.trace("Loading serviceParameterName property: {} ", this.serviceParameterName);
setEncodeServiceUrl(parseBoolean(getPropertyFromInitParams(filterConfig, "encodeServiceUrl", "true")));
logger.trace("Loading encodeServiceUrl property: {}", this.encodeServiceUrl);
initInternal(filterConfig);
}
init();
}
/** Controls the ordering of filter initialization and checking by defining a method that runs before the init.
* @param filterConfig the original filter configuration.
* @throws ServletException if there is a problem.
@ -147,7 +148,7 @@ public abstract class AbstractCasFilter extends AbstractConfigurationFilter {
public final String getServiceParameterName() {
return this.serviceParameterName;
}
/**
* Template method to allow you to change how you retrieve the ticket.
*

View File

@ -254,4 +254,4 @@ public abstract class AbstractTicketValidationFilter extends AbstractCasFilter {
public final void setUseSession(final boolean useSession) {
this.useSession = useSession;
}
}
}

View File

@ -19,13 +19,17 @@
package org.jasig.cas.client.authentication;
import static org.junit.Assert.*;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLEncoder;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.AssertionImpl;
import org.junit.After;
@ -37,7 +41,6 @@ import org.springframework.mock.web.*;
* Tests for the AuthenticationFilter.
*
* @author Scott Battaglia
* @version $Revision: 11753 $ $Date: 2007-01-03 13:37:26 -0500 (Wed, 03 Jan 2007) $
* @since 3.0
*/
public final class AuthenticationFilterTests {
@ -50,11 +53,10 @@ public final class AuthenticationFilterTests {
@Before
public void setUp() throws Exception {
// TODO CAS_SERVICE_URL, false, CAS_LOGIN_URL
this.filter = new AuthenticationFilter();
final MockFilterConfig config = new MockFilterConfig();
config.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);
config.addInitParameter("service", "https://localhost:8443/service");
config.addInitParameter("service", CAS_SERVICE_URL);
this.filter.init(config);
}
@ -184,7 +186,7 @@ public final class AuthenticationFilterTests {
final AuthenticationFilter f = new AuthenticationFilter();
final MockFilterConfig config = new MockFilterConfig();
config.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);
config.addInitParameter("service", "https://localhost:8443/service");
config.addInitParameter("service", CAS_SERVICE_URL);
config.addInitParameter("renew", "true");
try {
f.init(config);
@ -198,8 +200,8 @@ public final class AuthenticationFilterTests {
public void testAllowsRenewContextParam() throws Exception {
final AuthenticationFilter f = new AuthenticationFilter();
final MockServletContext context = new MockServletContext();
context.addInitParameter("casServerLoginUrl", "https://cas.example.com/login");
context.addInitParameter("service", "https://localhost:8443/service");
context.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);
context.addInitParameter("service", CAS_SERVICE_URL);
context.addInitParameter("renew", "true");
f.init(new MockFilterConfig(context));
final Field renewField = AuthenticationFilter.class.getDeclaredField("renew");
@ -211,10 +213,159 @@ public final class AuthenticationFilterTests {
public void customRedirectStrategy() throws Exception {
final AuthenticationFilter f = new AuthenticationFilter();
final MockServletContext context = new MockServletContext();
context.addInitParameter("casServerLoginUrl", "https://cas.example.com/login");
context.addInitParameter("service", "https://localhost:8443/service");
context.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);
context.addInitParameter("service", CAS_SERVICE_URL);
context.addInitParameter("authenticationRedirectStrategyClass",
"org.jasig.cas.client.authentication.FacesCompatibleAuthenticationRedirectStrategy");
f.init(new MockFilterConfig(context));
}
@Test
public void testIgnorePatterns() throws Exception {
final AuthenticationFilter f = new AuthenticationFilter();
final MockServletContext context = new MockServletContext();
context.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);
context.addInitParameter("ignorePattern", "=valueTo(\\w+)");
context.addInitParameter("service", CAS_SERVICE_URL);
f.init(new MockFilterConfig(context));
final MockHttpServletRequest request = new MockHttpServletRequest();
final String URL = CAS_SERVICE_URL + "?param=valueToIgnore";
request.setRequestURI(URL);
final MockHttpSession session = new MockHttpSession();
request.setSession(session);
final MockHttpServletResponse response = new MockHttpServletResponse();
final FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
}
};
f.doFilter(request, response, filterChain);
assertNull(response.getRedirectedUrl());
}
@Test
public void testIgnorePatternsWithContainsMatching() throws Exception {
final AuthenticationFilter f = new AuthenticationFilter();
final MockServletContext context = new MockServletContext();
context.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);
context.addInitParameter("ignorePattern", "=valueToIgnore");
context.addInitParameter("ignoreUrlPatternType", "CONTAINS");
context.addInitParameter("service", CAS_SERVICE_URL);
f.init(new MockFilterConfig(context));
final MockHttpServletRequest request = new MockHttpServletRequest();
final String URL = CAS_SERVICE_URL + "?param=valueToIgnore";
request.setRequestURI(URL);
final MockHttpSession session = new MockHttpSession();
request.setSession(session);
final MockHttpServletResponse response = new MockHttpServletResponse();
final FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
}
};
f.doFilter(request, response, filterChain);
assertNull(response.getRedirectedUrl());
}
@Test
public void testIgnorePatternsWithExactMatching() throws Exception {
final AuthenticationFilter f = new AuthenticationFilter();
final MockServletContext context = new MockServletContext();
context.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);
final URL url = new URL(CAS_SERVICE_URL + "?param=valueToIgnore");
context.addInitParameter("ignorePattern", url.toExternalForm());
context.addInitParameter("ignoreUrlPatternType", "EXACT");
context.addInitParameter("service", CAS_SERVICE_URL);
f.init(new MockFilterConfig(context));
final MockHttpServletRequest request = new MockHttpServletRequest();
request.setScheme(url.getProtocol());
request.setServerName(url.getHost());
request.setServerPort(url.getPort());
request.setQueryString(url.getQuery());
request.setRequestURI(url.getPath());
final MockHttpSession session = new MockHttpSession();
request.setSession(session);
final MockHttpServletResponse response = new MockHttpServletResponse();
final FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
}
};
f.doFilter(request, response, filterChain);
assertNull(response.getRedirectedUrl());
}
@Test
public void testIgnorePatternsWithExactClassname() throws Exception {
final AuthenticationFilter f = new AuthenticationFilter();
final MockServletContext context = new MockServletContext();
context.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);
context.addInitParameter("ignorePattern", "=valueToIgnore");
context.addInitParameter("ignoreUrlPatternType", ContainsPatternUrlPatternMatcherStrategy.class.getName());
context.addInitParameter("service", CAS_SERVICE_URL);
f.init(new MockFilterConfig(context));
final MockHttpServletRequest request = new MockHttpServletRequest();
final String URL = CAS_SERVICE_URL + "?param=valueToIgnore";
request.setRequestURI(URL);
final MockHttpSession session = new MockHttpSession();
request.setSession(session);
final MockHttpServletResponse response = new MockHttpServletResponse();
final FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
}
};
f.doFilter(request, response, filterChain);
assertNull(response.getRedirectedUrl());
}
@Test
public void testIgnorePatternsWithInvalidClassname() throws Exception {
final AuthenticationFilter f = new AuthenticationFilter();
final MockServletContext context = new MockServletContext();
context.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);
context.addInitParameter("ignorePattern", "=valueToIgnore");
context.addInitParameter("ignoreUrlPatternType", "unknown.class.name");
context.addInitParameter("service", CAS_SERVICE_URL);
f.init(new MockFilterConfig(context));
final MockHttpServletRequest request = new MockHttpServletRequest();
final String URL = CAS_SERVICE_URL + "?param=valueToIgnore";
request.setRequestURI(URL);
final MockHttpSession session = new MockHttpSession();
request.setSession(session);
final MockHttpServletResponse response = new MockHttpServletResponse();
final FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
}
};
f.doFilter(request, response, filterChain);
System.out.println(response.getRedirectedUrl());
}
}

View File

@ -54,4 +54,4 @@ public class Cas10TicketValidationFilterTests {
assertTrue(validator instanceof Cas10TicketValidator);
assertTrue(((Cas10TicketValidator) validator).isRenew());
}
}
}

View File

@ -54,4 +54,4 @@ public class Saml11TicketValidationFilterTests {
assertTrue(validator instanceof Saml11TicketValidator);
assertTrue(((Saml11TicketValidator) validator).isRenew());
}
}
}

View File

@ -141,4 +141,4 @@ public final class Saml11TicketValidatorTests extends AbstractTicketValidatorTes
private Interval currentTimeRangeInterval() {
return new Interval(new DateTime(DateTimeZone.UTC).minus(5000), new DateTime(DateTimeZone.UTC).plus(200000000));
}
}
}