Merge pull request #51 from battags/master

[NOJIRA] Reformat to Eclipse Standard
This commit is contained in:
Scott 2013-06-19 19:55:55 -07:00
commit 7e5b8426a4
126 changed files with 1902 additions and 1993 deletions

View File

@ -1,106 +1,106 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<parent>
<groupId>org.jasig.cas.client</groupId>
<version>3.3-SNAPSHOT</version>
<artifactId>cas-client</artifactId>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.jasig.cas.client</groupId>
<version>3.3-SNAPSHOT</version>
<artifactId>cas-client</artifactId>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<packaging>jar</packaging>
<name>Jasig CAS Client for Java - Core</name>
<artifactId>cas-client-core</artifactId>
<packaging>jar</packaging>
<name>Jasig CAS Client for Java - Core</name>
<dependencies>
<dependency>
<groupId>xml-security</groupId>
<artifactId>xmlsec</artifactId>
<version>1.3.0</version>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependencies>
<dependency>
<groupId>xml-security</groupId>
<artifactId>xmlsec</artifactId>
<version>1.3.0</version>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.opensaml</groupId>
<artifactId>opensaml</artifactId>
<version>${opensaml.version}</version>
<type>jar</type>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.opensaml</groupId>
<artifactId>opensaml</artifactId>
<version>${opensaml.version}</version>
<type>jar</type>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.4</version>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.4</version>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<scope>test</scope>
<version>1.2.15</version>
<exclusions>
<exclusion>
<artifactId>jmxri</artifactId>
<groupId>com.sun.jmx</groupId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<scope>test</scope>
<version>1.2.15</version>
<exclusions>
<exclusion>
<artifactId>jmxri</artifactId>
<groupId>com.sun.jmx</groupId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>
<spring.version>3.1.3.RELEASE</spring.version>
<opensaml.version>2.5.1-1</opensaml.version>
</properties>
<properties>
<spring.version>3.1.3.RELEASE</spring.version>
<opensaml.version>2.5.1-1</opensaml.version>
</properties>
</project>

View File

@ -47,6 +47,6 @@ public interface AttributePrincipal extends Principal, Serializable {
* The Map of key/value pairs associated with this principal.
* @return the map of key/value pairs associated with this principal.
*/
Map<String,Object> getAttributes();
Map<String, Object> getAttributes();
}

View File

@ -18,14 +18,13 @@
*/
package org.jasig.cas.client.authentication;
import java.util.Collections;
import java.util.Map;
import org.jasig.cas.client.proxy.ProxyRetriever;
import org.jasig.cas.client.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.Map;
/**
* Concrete implementation of the AttributePrincipal interface.
*
@ -40,7 +39,7 @@ public class AttributePrincipalImpl extends SimplePrincipal implements Attribute
private static final long serialVersionUID = -1443182634624927187L;
/** Map of key/value pairs about this principal. */
private final Map<String,Object> attributes;
private final Map<String, Object> attributes;
/** The CAS 2 ticket used to retrieve a proxy ticket. */
private final String proxyGrantingTicket;
@ -54,7 +53,7 @@ public class AttributePrincipalImpl extends SimplePrincipal implements Attribute
* @param name the unique identifier for the principal.
*/
public AttributePrincipalImpl(final String name) {
this(name, Collections.<String, Object>emptyMap());
this(name, Collections.<String, Object> emptyMap());
}
/**
@ -63,8 +62,8 @@ public class AttributePrincipalImpl extends SimplePrincipal implements Attribute
* @param name the unique identifier for the principal.
* @param attributes the key/value pairs for this principal.
*/
public AttributePrincipalImpl(final String name, final Map<String,Object> attributes) {
this(name, attributes, null, null);
public AttributePrincipalImpl(final String name, final Map<String, Object> attributes) {
this(name, attributes, null, null);
}
/**
@ -74,8 +73,9 @@ public class AttributePrincipalImpl extends SimplePrincipal implements Attribute
* @param proxyGrantingTicket the ticket associated with this principal.
* @param proxyRetriever the ProxyRetriever implementation to call back to the CAS server.
*/
public AttributePrincipalImpl(final String name, final String proxyGrantingTicket, final ProxyRetriever proxyRetriever) {
this(name, Collections.<String, Object>emptyMap(), proxyGrantingTicket, proxyRetriever);
public AttributePrincipalImpl(final String name, final String proxyGrantingTicket,
final ProxyRetriever proxyRetriever) {
this(name, Collections.<String, Object> emptyMap(), proxyGrantingTicket, proxyRetriever);
}
/**
@ -86,7 +86,8 @@ public class AttributePrincipalImpl extends SimplePrincipal implements Attribute
* @param proxyGrantingTicket the ticket associated with this principal.
* @param proxyRetriever the ProxyRetriever implementation to call back to the CAS server.
*/
public AttributePrincipalImpl(final String name, final Map<String,Object> attributes, final String proxyGrantingTicket, final ProxyRetriever proxyRetriever) {
public AttributePrincipalImpl(final String name, final Map<String, Object> attributes,
final String proxyGrantingTicket, final ProxyRetriever proxyRetriever) {
super(name);
this.attributes = attributes;
this.proxyGrantingTicket = proxyGrantingTicket;
@ -95,7 +96,7 @@ public class AttributePrincipalImpl extends SimplePrincipal implements Attribute
CommonUtils.assertNotNull(this.attributes, "attributes cannot be null.");
}
public Map<String,Object> getAttributes() {
public Map<String, Object> getAttributes() {
return this.attributes;
}
@ -103,8 +104,8 @@ public class AttributePrincipalImpl extends SimplePrincipal implements Attribute
if (proxyGrantingTicket != null) {
return this.proxyRetriever.getProxyTicketIdFor(this.proxyGrantingTicket, service);
}
LOGGER.debug("No ProxyGrantingTicket was supplied, so no Proxy Ticket can be retrieved.");
LOGGER.debug("No ProxyGrantingTicket was supplied, so no Proxy Ticket can be retrieved.");
return null;
}
}

View File

@ -1,8 +1,8 @@
package org.jasig.cas.client.authentication;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Interface to abstract the authentication strategy for redirecting. The traditional method was to always just redirect,
@ -22,6 +22,7 @@ public interface AuthenticationRedirectStrategy {
* @param potentialRedirectUrl the url that might be used (there are no guarantees of course!)
* @throws IOException the exception to throw if there is some type of error. This will bubble up through the filter.
*/
void redirect(HttpServletRequest request, HttpServletResponse response, String potentialRedirectUrl) throws IOException;
void redirect(HttpServletRequest request, HttpServletResponse response, String potentialRedirectUrl)
throws IOException;
}

View File

@ -1,8 +1,8 @@
package org.jasig.cas.client.authentication;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Implementation of the {@link AuthenticationRedirectStrategy} class that preserves the original behavior that existed prior to 3.3.0.
@ -12,7 +12,8 @@ import java.io.IOException;
*/
public final class DefaultAuthenticationRedirectStrategy implements AuthenticationRedirectStrategy {
public void redirect(final HttpServletRequest request, final HttpServletResponse response, final String potentialRedirectUrl) throws IOException {
public void redirect(final HttpServletRequest request, final HttpServletResponse response,
final String potentialRedirectUrl) throws IOException {
response.sendRedirect(potentialRedirectUrl);
}
}

View File

@ -22,23 +22,23 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public final class DefaultGatewayResolverImpl implements GatewayResolver {
public static final String CONST_CAS_GATEWAY = "_const_cas_gateway_";
public boolean hasGatewayedAlready(final HttpServletRequest request, final String serviceUrl) {
final HttpSession session = request.getSession(false);
if (session == null) {
return false;
}
final boolean result = session.getAttribute(CONST_CAS_GATEWAY) != null;
session.removeAttribute(CONST_CAS_GATEWAY);
return result;
}
public boolean hasGatewayedAlready(final HttpServletRequest request, final String serviceUrl) {
final HttpSession session = request.getSession(false);
public String storeGatewayInformation(final HttpServletRequest request, final String serviceUrl) {
request.getSession(true).setAttribute(CONST_CAS_GATEWAY, "yes");
return serviceUrl;
}
if (session == null) {
return false;
}
final boolean result = session.getAttribute(CONST_CAS_GATEWAY) != null;
session.removeAttribute(CONST_CAS_GATEWAY);
return result;
}
public String storeGatewayInformation(final HttpServletRequest request, final String serviceUrl) {
request.getSession(true).setAttribute(CONST_CAS_GATEWAY, "yes");
return serviceUrl;
}
}

View File

@ -1,11 +1,10 @@
package org.jasig.cas.client.authentication;
import org.jasig.cas.client.util.CommonUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jasig.cas.client.util.CommonUtils;
/**
* Implementation of the redirect strategy that can handle a Faces Ajax request in addition to the standard redirect style.
@ -17,7 +16,8 @@ public final class FacesCompatibleAuthenticationRedirectStrategy implements Auth
private static final String FACES_PARTIAL_AJAX_PARAMETER = "javax.faces.partial.ajax";
public void redirect(final HttpServletRequest request, final HttpServletResponse response, final String potentialRedirectUrl) throws IOException {
public void redirect(final HttpServletRequest request, final HttpServletResponse response,
final String potentialRedirectUrl) throws IOException {
if (CommonUtils.isNotBlank(request.getParameter(FACES_PARTIAL_AJAX_PARAMETER))) {
// this is an ajax request - redirect ajaxly
@ -26,7 +26,8 @@ public final class FacesCompatibleAuthenticationRedirectStrategy implements Auth
final PrintWriter writer = response.getWriter();
writer.write("<?xml version='1.0' encoding='UTF-8'?>");
writer.write(String.format("<partial-response><redirect url=\"%s\"></redirect></partial-response>", potentialRedirectUrl));
writer.write(String.format("<partial-response><redirect url=\"%s\"></redirect></partial-response>",
potentialRedirectUrl));
} else {
response.sendRedirect(potentialRedirectUrl);
}

View File

@ -31,21 +31,21 @@ import javax.servlet.http.HttpServletRequest;
*/
public interface GatewayResolver {
/**
* Determines if the request has been gatewayed already. Should also do gateway clean up.
*
* @param request the Http Servlet Request
* @param serviceUrl the service url
* @return true if yes, false otherwise.
*/
boolean hasGatewayedAlready(HttpServletRequest request, String serviceUrl);
/**
* Storage the request for gatewaying and return the service url, which can be modified.
*
* @param request the HttpServletRequest.
* @param serviceUrl the service url
* @return the potentially modified service url to redirect to
*/
String storeGatewayInformation(HttpServletRequest request, String serviceUrl);
/**
* Determines if the request has been gatewayed already. Should also do gateway clean up.
*
* @param request the Http Servlet Request
* @param serviceUrl the service url
* @return true if yes, false otherwise.
*/
boolean hasGatewayedAlready(HttpServletRequest request, String serviceUrl);
/**
* Storage the request for gatewaying and return the service url, which can be modified.
*
* @param request the HttpServletRequest.
* @param serviceUrl the service url
* @return the potentially modified service url to redirect to
*/
String storeGatewayInformation(HttpServletRequest request, String serviceUrl);
}

View File

@ -64,7 +64,7 @@ public final class SimpleGroup extends SimplePrincipal implements Group {
public boolean removeMember(final Principal user) {
return this.members.remove(user);
}
public String toString() {
return super.toString() + ": " + members.toString();
}

View File

@ -20,7 +20,6 @@ package org.jasig.cas.client.authentication;
import java.io.Serializable;
import java.security.Principal;
import org.jasig.cas.client.util.CommonUtils;
/**
@ -62,7 +61,7 @@ public class SimplePrincipal implements Principal, Serializable {
} else if (!(o instanceof SimplePrincipal)) {
return false;
} else {
return getName().equals(((SimplePrincipal)o).getName());
return getName().equals(((SimplePrincipal) o).getName());
}
}

View File

@ -19,7 +19,6 @@
package org.jasig.cas.client.jaas;
import java.io.Serializable;
import org.jasig.cas.client.authentication.SimplePrincipal;
import org.jasig.cas.client.validation.Assertion;
@ -32,7 +31,7 @@ import org.jasig.cas.client.validation.Assertion;
*
*/
public class AssertionPrincipal extends SimplePrincipal implements Serializable {
/** AssertionPrincipal.java */
private static final long serialVersionUID = 2288520214366461693L;

View File

@ -25,25 +25,12 @@ import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.security.Principal;
import java.security.acl.Group;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.callback.*;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import org.jasig.cas.client.authentication.SimpleGroup;
import org.jasig.cas.client.authentication.SimplePrincipal;
import org.jasig.cas.client.util.CommonUtils;
@ -116,14 +103,14 @@ import org.slf4j.LoggerFactory;
public class CasLoginModule implements LoginModule {
/** Constant for login name stored in shared state. */
public static final String LOGIN_NAME = "javax.security.auth.login.name";
/**
* Default group name for storing caller principal.
* The default value supports JBoss, but is configurable to hopefully
* support other JEE containers.
*/
public static final String DEFAULT_PRINCIPAL_GROUP_NAME = "CallerPrincipal";
/**
* Default group name for storing role membership data.
* The default value supports JBoss, but is configurable to hopefully
@ -145,41 +132,41 @@ public class CasLoginModule implements LoginModule {
* CAS tickets are one-time-use, a cached assertion must be provided on
* re-authentication.
*/
protected static final Map<TicketCredential,Assertion> ASSERTION_CACHE = new HashMap<TicketCredential,Assertion>();
protected static final Map<TicketCredential, Assertion> ASSERTION_CACHE = new HashMap<TicketCredential, Assertion>();
/** Logger instance */
protected final Logger logger = LoggerFactory.getLogger(getClass());
/** JAAS authentication subject */
protected Subject subject;
/** JAAS callback handler */
protected CallbackHandler callbackHandler;
/** CAS ticket validator */
protected TicketValidator ticketValidator;
/** CAS service parameter used if no service is provided via TextCallback on login */
protected String service;
/** CAS assertion */
protected Assertion assertion;
/** CAS ticket credential */
protected TicketCredential ticket;
/** Login module shared state */
protected Map<String,Object> sharedState;
protected Map<String, Object> sharedState;
/** Roles to be added to all authenticated principals by default */
protected String[] defaultRoles;
/** Names of attributes in the CAS assertion that should be used for role data */
protected Set<String> roleAttributeNames = new HashSet<String>();
/** Name of JAAS Group containing caller principal */
protected String principalGroupName = DEFAULT_PRINCIPAL_GROUP_NAME;
/** Name of JAAS Group containing role data */
protected String roleGroupName = DEFAULT_ROLE_GROUP_NAME;
@ -216,10 +203,7 @@ public class CasLoginModule implements LoginModule {
* names, e.g. DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS. Default unit is MINUTES.</li>
* </ul>
*/
public final void initialize(
final Subject subject,
final CallbackHandler handler,
final Map<String,?> state,
public final void initialize(final Subject subject, final CallbackHandler handler, final Map<String, ?> state,
final Map<String, ?> options) {
this.assertion = null;
@ -227,7 +211,7 @@ public class CasLoginModule implements LoginModule {
this.subject = subject;
this.sharedState = (Map<String, Object>) state;
this.sharedState = new HashMap<String, Object>(state);
String ticketValidatorClass = null;
for (final String key : options.keySet()) {
@ -251,7 +235,7 @@ public class CasLoginModule implements LoginModule {
logger.debug("Set roleAttributeNames={}", this.roleAttributeNames);
} else if ("principalGroupName".equals(key)) {
this.principalGroupName = (String) options.get(key);
logger.debug("Set principalGroupName={}",this.principalGroupName);
logger.debug("Set principalGroupName={}", this.principalGroupName);
} else if ("roleGroupName".equals(key)) {
this.roleGroupName = (String) options.get(key);
logger.debug("Set roleGroupName={}", this.roleGroupName);
@ -311,15 +295,15 @@ public class CasLoginModule implements LoginModule {
logger.info("Login failed due to IO exception in callback handler: {}", e);
throw (LoginException) new LoginException("IO exception in callback handler: " + e).initCause(e);
} catch (final UnsupportedCallbackException e) {
logger.info("Login failed due to unsupported callback: {}", e);
logger.info("Login failed due to unsupported callback: {}", e);
throw (LoginException) new LoginException(
"Callback handler does not support PasswordCallback and TextInputCallback.").initCause(e);
}
if (ticketCallback.getPassword() != null) {
this.ticket = new TicketCredential(new String(ticketCallback.getPassword()));
final String service = CommonUtils.isNotBlank(
serviceCallback.getName()) ? serviceCallback.getName() : this.service;
final String service = CommonUtils.isNotBlank(serviceCallback.getName()) ? serviceCallback.getName()
: this.service;
if (this.cacheAssertions) {
this.assertion = ASSERTION_CACHE.get(ticket);
@ -336,7 +320,8 @@ public class CasLoginModule implements LoginModule {
"Neither login module nor callback handler provided required service parameter.");
}
try {
logger.debug("Attempting ticket validation with service={} and ticket={}", service, this.ticket);
logger.debug("Attempting ticket validation with service={} and ticket={}", service,
this.ticket);
this.assertion = this.ticketValidator.validate(this.ticket.getName(), service);
} catch (final Exception e) {
@ -398,8 +383,8 @@ public class CasLoginModule implements LoginModule {
throw new LoginException("Ticket credential not found.");
}
final AssertionPrincipal casPrincipal = new AssertionPrincipal(
this.assertion.getPrincipal().getName(), this.assertion);
final AssertionPrincipal casPrincipal = new AssertionPrincipal(this.assertion.getPrincipal().getName(),
this.assertion);
this.subject.getPrincipals().add(casPrincipal);
// Add group containing principal as sole member
@ -415,7 +400,7 @@ public class CasLoginModule implements LoginModule {
roleGroup.addMember(new SimplePrincipal(defaultRole));
}
final Map<String,Object> attributes = this.assertion.getPrincipal().getAttributes();
final Map<String, Object> attributes = this.assertion.getPrincipal().getAttributes();
for (final String key : attributes.keySet()) {
if (this.roleAttributeNames.contains(key)) {
// Attribute value is Object if singular or Collection if plural
@ -465,7 +450,7 @@ public class CasLoginModule implements LoginModule {
removePrincipalsOfType(AssertionPrincipal.class);
removePrincipalsOfType(SimplePrincipal.class);
removePrincipalsOfType(SimpleGroup.class);
// Remove all CAS credentials
removeCredentialsOfType(TicketCredential.class);
@ -490,19 +475,20 @@ public class CasLoginModule implements LoginModule {
protected void postLogout() {
// template method
}
/**
* Creates a {@link TicketValidator} instance from a class name and map of property name/value pairs.
* @param className Fully-qualified name of {@link TicketValidator} concrete class.
* @param propertyMap Map of property name/value pairs to set on validator instance.
* @return Ticket validator with properties set.
*/
private TicketValidator createTicketValidator(final String className, final Map<String,?> propertyMap) {
CommonUtils.assertTrue(
propertyMap.containsKey("casServerUrlPrefix"), "Required property casServerUrlPrefix not found.");
private TicketValidator createTicketValidator(final String className, final Map<String, ?> propertyMap) {
CommonUtils.assertTrue(propertyMap.containsKey("casServerUrlPrefix"),
"Required property casServerUrlPrefix not found.");
final Class<TicketValidator> validatorClass = ReflectUtils.loadClass(className);
final TicketValidator validator = ReflectUtils.newInstance(
validatorClass, propertyMap.get("casServerUrlPrefix"));
final TicketValidator validator = ReflectUtils.newInstance(validatorClass,
propertyMap.get("casServerUrlPrefix"));
try {
final BeanInfo info = Introspector.getBeanInfo(validatorClass);
@ -513,8 +499,8 @@ public class CasLoginModule implements LoginModule {
final String value = (String) propertyMap.get(property);
final PropertyDescriptor pd = ReflectUtils.getPropertyDescriptor(info, property);
if (pd != null) {
ReflectUtils.setProperty(property, convertIfNecessary(pd, value), validator, info);
logger.debug("Set {} = {}", property, value);
ReflectUtils.setProperty(property, convertIfNecessary(pd, value), validator, info);
logger.debug("Set {} = {}", property, value);
} else {
logger.warn("Cannot find property {} on {}", property, className);
}
@ -523,7 +509,7 @@ public class CasLoginModule implements LoginModule {
} catch (final IntrospectionException e) {
throw new RuntimeException("Error getting bean info for " + validatorClass, e);
}
return validator;
}
@ -547,8 +533,8 @@ public class CasLoginModule implements LoginModule {
} else if (long.class.equals(pd.getPropertyType())) {
return new Long(value);
} else {
throw new IllegalArgumentException(
"No conversion strategy exists for property " + pd.getName() + " of type " + pd.getPropertyType());
throw new IllegalArgumentException("No conversion strategy exists for property " + pd.getName()
+ " of type " + pd.getPropertyType());
}
}
@ -567,11 +553,12 @@ public class CasLoginModule implements LoginModule {
private void removeCredentialsOfType(final Class<? extends Principal> clazz) {
this.subject.getPrivateCredentials().removeAll(this.subject.getPrivateCredentials(clazz));
}
/**
* Removes expired entries from the assertion cache.
*/
private void cleanCache() {
logger.debug("Cleaning assertion cache of size {}", ASSERTION_CACHE.size());
logger.debug("Cleaning assertion cache of size {}", ASSERTION_CACHE.size());
final Iterator<Map.Entry<TicketCredential, Assertion>> iter = ASSERTION_CACHE.entrySet().iterator();
final Calendar cutoff = Calendar.getInstance();
cutoff.setTimeInMillis(System.currentTimeMillis() - this.cacheTimeoutUnit.toMillis(this.cacheTimeout));
@ -586,4 +573,3 @@ public class CasLoginModule implements LoginModule {
}
}
}

View File

@ -19,12 +19,7 @@
package org.jasig.cas.client.jaas;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.callback.*;
/**
* Callback handler that provides the CAS service and ticket to a
@ -40,10 +35,10 @@ public class ServiceAndTicketCallbackHandler implements CallbackHandler {
/** CAS service URL */
private final String service;
/** CAS service ticket */
private final String ticket;
/**
* Creates a new instance with the given service and ticket.
*

View File

@ -32,7 +32,7 @@ public final class TicketCredential implements Principal {
/** Hash code seed value */
private static final int HASHCODE_SEED = 17;
/** Ticket ID string */
private String ticket;
@ -53,12 +53,15 @@ public final class TicketCredential implements Principal {
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final TicketCredential that = (TicketCredential) o;
if (ticket != null ? !ticket.equals(that.ticket) : that.ticket != null) return false;
if (ticket != null ? !ticket.equals(that.ticket) : that.ticket != null)
return false;
return true;
}

View File

@ -18,13 +18,13 @@
*/
package org.jasig.cas.client.proxy;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
/**
* Provides encryption capabilities. Not entirely safe to configure since we have no way of controlling the
@ -42,7 +42,8 @@ public abstract class AbstractEncryptedProxyGrantingTicketStorageImpl implements
private String cipherAlgorithm = DEFAULT_ENCRYPTION_ALGORITHM;
public final void setSecretKey(final String key) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
public final void setSecretKey(final String key) throws NoSuchAlgorithmException, InvalidKeyException,
InvalidKeySpecException {
this.key = SecretKeyFactory.getInstance(this.cipherAlgorithm).generateSecret(new DESedeKeySpec(key.getBytes()));
}

View File

@ -18,17 +18,14 @@
*/
package org.jasig.cas.client.proxy;
import java.net.URL;
import java.net.URLEncoder;
import org.jasig.cas.client.ssl.HttpURLConnectionFactory;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.util.XmlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Implementation of a ProxyRetriever that follows the CAS 2.0 specification.
* For more information on the CAS 2.0 specification, please see the <a
@ -44,7 +41,7 @@ import java.net.URLEncoder;
public final class Cas20ProxyRetriever implements ProxyRetriever {
/** Unique Id for serialization. */
private static final long serialVersionUID = 560409469568911792L;
private static final long serialVersionUID = 560409469568911792L;
private static final Logger logger = LoggerFactory.getLogger(Cas20ProxyRetriever.class);
@ -57,7 +54,7 @@ public final class Cas20ProxyRetriever implements ProxyRetriever {
/** Url connection factory to use when communicating with the server **/
private final HttpURLConnectionFactory urlConnectionFactory;
/**
* Main Constructor.
*
@ -65,34 +62,34 @@ public final class Cas20ProxyRetriever implements ProxyRetriever {
* @param encoding the encoding to use.
* @param urlFactory url connection factory use when retrieving proxy responses from the server
*/
public Cas20ProxyRetriever(final String casServerUrl, final String encoding, final HttpURLConnectionFactory urlFactory) {
public Cas20ProxyRetriever(final String casServerUrl, final String encoding,
final HttpURLConnectionFactory urlFactory) {
CommonUtils.assertNotNull(casServerUrl, "casServerUrl cannot be null.");
this.casServerUrl = casServerUrl;
this.encoding = encoding;
this.urlConnectionFactory = urlFactory;
}
public String getProxyTicketIdFor(final String proxyGrantingTicketId, final String targetService) {
CommonUtils.assertNotNull(proxyGrantingTicketId, "proxyGrantingTicketId cannot be null.");
CommonUtils.assertNotNull(targetService, "targetService cannot be null.");
final URL url = constructUrl(proxyGrantingTicketId, targetService);
final String response = CommonUtils.getResponseFromServer(url, this.urlConnectionFactory, this.encoding);
final String error = XmlUtils.getTextForElement(response, "proxyFailure");
if (CommonUtils.isNotEmpty(error)) {
logger.debug(error);
return null;
}
return XmlUtils.getTextForElement(response, "proxyTicket");
}
private URL constructUrl(final String proxyGrantingTicketId, final String targetService) {
try {
return new URL(this.casServerUrl + (this.casServerUrl.endsWith("/") ? "" : "/") + "proxy"
+ "?pgt=" + proxyGrantingTicketId
+ "&targetService=" + URLEncoder.encode(targetService, "UTF-8"));
return new URL(this.casServerUrl + (this.casServerUrl.endsWith("/") ? "" : "/") + "proxy" + "?pgt="
+ proxyGrantingTicketId + "&targetService=" + URLEncoder.encode(targetService, "UTF-8"));
} catch (final Exception e) {
throw new RuntimeException(e);
}

View File

@ -38,6 +38,7 @@ public final class CleanUpTimerTask extends TimerTask {
public CleanUpTimerTask(final ProxyGrantingTicketStorage proxyGrantingTicketStorage) {
this.proxyGrantingTicketStorage = proxyGrantingTicketStorage;
}
public void run() {
this.proxyGrantingTicketStorage.cleanUp();
}

View File

@ -46,7 +46,7 @@ public interface ProxyGrantingTicketStorage {
* @return the ProxyGrantingTicket Id or null if it can't be found
*/
public String retrieve(String proxyGrantingTicketIou);
/**
* Called on a regular basis by an external timer,
* giving implementations a chance to remove stale data.

View File

@ -18,10 +18,9 @@
*/
package org.jasig.cas.client.proxy;
import java.util.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.jasig.cas.client.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -39,8 +38,8 @@ import org.slf4j.LoggerFactory;
* @since 3.0
*/
public final class ProxyGrantingTicketStorageImpl implements ProxyGrantingTicketStorage {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* Default timeout in milliseconds.
@ -50,7 +49,7 @@ public final class ProxyGrantingTicketStorageImpl implements ProxyGrantingTicket
/**
* Map that stores the PGTIOU to PGT mappings.
*/
private final ConcurrentMap<String,ProxyGrantingTicketHolder> cache = new ConcurrentHashMap<String,ProxyGrantingTicketHolder>();
private final ConcurrentMap<String, ProxyGrantingTicketHolder> cache = new ConcurrentHashMap<String, ProxyGrantingTicketHolder>();
/**
* time, in milliseconds, before a {@link ProxyGrantingTicketHolder}
@ -58,7 +57,7 @@ public final class ProxyGrantingTicketStorageImpl implements ProxyGrantingTicket
*
* @see ProxyGrantingTicketStorageImpl#DEFAULT_TIMEOUT
*/
private long timeout;
private long timeout;
/**
* Constructor set the timeout to the default value.
@ -74,7 +73,7 @@ public final class ProxyGrantingTicketStorageImpl implements ProxyGrantingTicket
* @param timeout the time to hold on to the ProxyGrantingTicket
*/
public ProxyGrantingTicketStorageImpl(final long timeout) {
this.timeout = timeout;
this.timeout = timeout;
}
/**
@ -89,7 +88,7 @@ public final class ProxyGrantingTicketStorageImpl implements ProxyGrantingTicket
final ProxyGrantingTicketHolder holder = this.cache.get(proxyGrantingTicketIou);
if (holder == null) {
logger.info("No Proxy Ticket found for [{}].", proxyGrantingTicketIou);
logger.info("No Proxy Ticket found for [{}].", proxyGrantingTicketIou);
return null;
}
@ -102,7 +101,8 @@ public final class ProxyGrantingTicketStorageImpl implements ProxyGrantingTicket
public void save(final String proxyGrantingTicketIou, final String proxyGrantingTicket) {
final ProxyGrantingTicketHolder holder = new ProxyGrantingTicketHolder(proxyGrantingTicket);
logger.debug("Saving ProxyGrantingTicketIOU and ProxyGrantingTicket combo: [{}, {}]", proxyGrantingTicketIou, proxyGrantingTicket);
logger.debug("Saving ProxyGrantingTicketIOU and ProxyGrantingTicket combo: [{}, {}]", proxyGrantingTicketIou,
proxyGrantingTicket);
this.cache.put(proxyGrantingTicketIou, holder);
}
@ -111,13 +111,13 @@ public final class ProxyGrantingTicketStorageImpl implements ProxyGrantingTicket
* called regularly via an external thread or timer.
*/
public void cleanUp() {
for (final Map.Entry<String,ProxyGrantingTicketHolder> holder : this.cache.entrySet()) {
for (final Map.Entry<String, ProxyGrantingTicketHolder> holder : this.cache.entrySet()) {
if (holder.getValue().isExpired(this.timeout)) {
this.cache.remove(holder.getKey());
}
}
}
private static final class ProxyGrantingTicketHolder {
private final String proxyGrantingTicket;

View File

@ -18,13 +18,11 @@
*/
package org.jasig.cas.client.session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HashMap backed implementation of SessionMappingStorage.
@ -35,26 +33,26 @@ import javax.servlet.http.HttpSession;
*
*/
public final class HashMapBackedSessionMappingStorage implements SessionMappingStorage {
/**
* Maps the ID from the CAS server to the Session.
*/
private final Map<String,HttpSession> MANAGED_SESSIONS = new HashMap<String,HttpSession>();
private final Map<String, HttpSession> MANAGED_SESSIONS = new HashMap<String, HttpSession>();
/**
* Maps the Session ID to the key from the CAS Server.
*/
private final Map<String,String> ID_TO_SESSION_KEY_MAPPING = new HashMap<String,String>();
private final Map<String, String> ID_TO_SESSION_KEY_MAPPING = new HashMap<String, String>();
private final Logger logger = LoggerFactory.getLogger(getClass());
public synchronized void addSessionById(String mappingId, HttpSession session) {
public synchronized void addSessionById(String mappingId, HttpSession session) {
ID_TO_SESSION_KEY_MAPPING.put(session.getId(), mappingId);
MANAGED_SESSIONS.put(mappingId, session);
}
}
public synchronized void removeBySessionById(final String sessionId) {
public synchronized void removeBySessionById(final String sessionId) {
logger.debug("Attempting to remove Session=[{}]", sessionId);
final String key = ID_TO_SESSION_KEY_MAPPING.get(sessionId);
@ -68,15 +66,15 @@ public final class HashMapBackedSessionMappingStorage implements SessionMappingS
}
MANAGED_SESSIONS.remove(key);
ID_TO_SESSION_KEY_MAPPING.remove(sessionId);
}
}
public synchronized HttpSession removeSessionByMappingId(String mappingId) {
final HttpSession session = MANAGED_SESSIONS.get(mappingId);
public synchronized HttpSession removeSessionByMappingId(String mappingId) {
final HttpSession session = MANAGED_SESSIONS.get(mappingId);
if (session != null) {
removeBySessionById(session.getId());
removeBySessionById(session.getId());
}
return session;
}
}
}

View File

@ -29,26 +29,26 @@ import javax.servlet.http.HttpSession;
*
*/
public interface SessionMappingStorage {
/**
* Remove the HttpSession based on the mappingId.
*
* @param mappingId the id the session is keyed under.
* @return the HttpSession if it exists.
*/
HttpSession removeSessionByMappingId(String mappingId);
/**
* Remove a session by its Id.
* @param sessionId the id of the session.
*/
void removeBySessionById(String sessionId);
/**
* Add a session by its mapping Id.
* @param mappingId the id to map the session to.
* @param session the HttpSession.
*/
void addSessionById(String mappingId, HttpSession session);
/**
* Remove the HttpSession based on the mappingId.
*
* @param mappingId the id the session is keyed under.
* @return the HttpSession if it exists.
*/
HttpSession removeSessionByMappingId(String mappingId);
/**
* Remove a session by its Id.
* @param sessionId the id of the session.
*/
void removeBySessionById(String sessionId);
/**
* Add a session by its mapping Id.
* @param mappingId the id to map the session to.
* @param session the HttpSession.
*/
void addSessionById(String mappingId, HttpSession session);
}

View File

@ -18,15 +18,10 @@
*/
package org.jasig.cas.client.session;
import org.jasig.cas.client.util.AbstractConfigurationFilter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import org.jasig.cas.client.util.AbstractConfigurationFilter;
/**
* Implements the Single Sign Out protocol. It handles registering the session and destroying the session.
@ -42,9 +37,12 @@ public final class SingleSignOutFilter extends AbstractConfigurationFilter {
public void init(final FilterConfig filterConfig) throws ServletException {
if (!isIgnoreInitConfiguration()) {
handler.setArtifactParameterName(getPropertyFromInitParams(filterConfig, "artifactParameterName", "ticket"));
handler.setLogoutParameterName(getPropertyFromInitParams(filterConfig, "logoutParameterName", "logoutRequest"));
handler.setArtifactParameterOverPost(parseBoolean(getPropertyFromInitParams(filterConfig, "artifactParameterOverPost", "false")));
handler.setEagerlyCreateSessions(parseBoolean(getPropertyFromInitParams(filterConfig, "eagerlyCreateSessions", "true")));
handler.setLogoutParameterName(getPropertyFromInitParams(filterConfig, "logoutParameterName",
"logoutRequest"));
handler.setArtifactParameterOverPost(parseBoolean(getPropertyFromInitParams(filterConfig,
"artifactParameterOverPost", "false")));
handler.setEagerlyCreateSessions(parseBoolean(getPropertyFromInitParams(filterConfig,
"eagerlyCreateSessions", "true")));
}
handler.init();
}
@ -52,7 +50,7 @@ public final class SingleSignOutFilter extends AbstractConfigurationFilter {
public void setArtifactParameterName(final String name) {
handler.setArtifactParameterName(name);
}
public void setLogoutParameterName(final String name) {
handler.setLogoutParameterName(name);
}
@ -60,8 +58,9 @@ public final class SingleSignOutFilter extends AbstractConfigurationFilter {
public void setSessionMappingStorage(final SessionMappingStorage storage) {
handler.setSessionMappingStorage(storage);
}
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
final FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
if (handler.isTokenRequest(request)) {
@ -80,7 +79,7 @@ public final class SingleSignOutFilter extends AbstractConfigurationFilter {
public void destroy() {
// nothing to do
}
protected static SingleSignOutHandler getSingleSignOutHandler() {
return handler;
}

View File

@ -18,17 +18,15 @@
*/
package org.jasig.cas.client.session;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.util.XmlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
/**
* Performs CAS single sign-out operations in an API-agnostic fashion.
*
@ -44,7 +42,7 @@ public final class SingleSignOutHandler {
/** Mapping of token IDs and session IDs to HTTP sessions */
private SessionMappingStorage sessionMappingStorage = new HashMapBackedSessionMappingStorage();
/** The name of the artifact parameter. This is used to capture the session identifier. */
private String artifactParameterName = "ticket";
@ -56,6 +54,7 @@ public final class SingleSignOutHandler {
private boolean eagerlyCreateSessions = true;
private List<String> safeParameters;
public void setSessionMappingStorage(final SessionMappingStorage storage) {
this.sessionMappingStorage = storage;
}
@ -100,7 +99,7 @@ public final class SingleSignOutHandler {
this.safeParameters = Arrays.asList(this.logoutParameterName);
}
}
/**
* Determines whether the given request contains an authentication token.
*
@ -109,7 +108,8 @@ public final class SingleSignOutHandler {
* @return True if request contains authentication token, false otherwise.
*/
public boolean isTokenRequest(final HttpServletRequest request) {
return CommonUtils.isNotBlank(CommonUtils.safeGetParameter(request, this.artifactParameterName, this.safeParameters));
return CommonUtils.isNotBlank(CommonUtils.safeGetParameter(request, this.artifactParameterName,
this.safeParameters));
}
/**
@ -120,8 +120,10 @@ public final class SingleSignOutHandler {
* @return True if request is logout request, false otherwise.
*/
public boolean isLogoutRequest(final HttpServletRequest request) {
return "POST".equals(request.getMethod()) && !isMultipartRequest(request) &&
CommonUtils.isNotBlank(CommonUtils.safeGetParameter(request, this.logoutParameterName, this.safeParameters));
return "POST".equals(request.getMethod())
&& !isMultipartRequest(request)
&& CommonUtils.isNotBlank(CommonUtils.safeGetParameter(request, this.logoutParameterName,
this.safeParameters));
}
/**
@ -148,15 +150,16 @@ public final class SingleSignOutHandler {
}
sessionMappingStorage.addSessionById(token, session);
}
/**
* Destroys the current HTTP session for the given CAS logout request.
*
* @param request HTTP request containing a CAS logout message.
*/
public void destroySession(final HttpServletRequest request) {
final String logoutMessage = CommonUtils.safeGetParameter(request, this.logoutParameterName, this.safeParameters);
logger.trace ("Logout request:\n{}", logoutMessage);
final String logoutMessage = CommonUtils.safeGetParameter(request, this.logoutParameterName,
this.safeParameters);
logger.trace("Logout request:\n{}", logoutMessage);
final String token = XmlUtils.getTextForElement(logoutMessage, "SessionIndex");
if (CommonUtils.isNotBlank(token)) {
@ -165,7 +168,7 @@ public final class SingleSignOutHandler {
if (session != null) {
String sessionID = session.getId();
logger.debug ("Invalidating session [{}] for token [{}]", sessionID, token);
logger.debug("Invalidating session [{}] for token [{}]", sessionID, token);
try {
session.invalidate();

View File

@ -34,16 +34,16 @@ import javax.servlet.http.HttpSessionListener;
*/
public final class SingleSignOutHttpSessionListener implements HttpSessionListener {
private SessionMappingStorage sessionMappingStorage;
private SessionMappingStorage sessionMappingStorage;
public void sessionCreated(final HttpSessionEvent event) {
// nothing to do at the moment
}
public void sessionDestroyed(final HttpSessionEvent event) {
if (sessionMappingStorage == null) {
sessionMappingStorage = getSessionMappingStorage();
}
if (sessionMappingStorage == null) {
sessionMappingStorage = getSessionMappingStorage();
}
final HttpSession session = event.getSession();
sessionMappingStorage.removeBySessionById(session.getId());
}
@ -55,6 +55,6 @@ public final class SingleSignOutHttpSessionListener implements HttpSessionListen
* @return the SessionMappingStorage
*/
protected static SessionMappingStorage getSessionMappingStorage() {
return SingleSignOutFilter.getSingleSignOutHandler().getSessionMappingStorage();
return SingleSignOutFilter.getSingleSignOutHandler().getSessionMappingStorage();
}
}

View File

@ -29,7 +29,7 @@ import java.net.URLConnection;
* @since 3.3
*/
public interface HttpURLConnectionFactory {
/**
* Receives a {@link URLConnection} instance typically as a result of a {@link URL}
* opening a connection to a remote resource. The received url connection is then

View File

@ -6,13 +6,7 @@ import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.security.KeyStore;
import java.util.Properties;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.*;
import org.jasig.cas.client.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -30,29 +24,30 @@ import org.slf4j.LoggerFactory;
public final class HttpsURLConnectionFactory implements HttpURLConnectionFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpsURLConnectionFactory.class);
/**
* Hostname verifier used when making an SSL request to the CAS server.
* Defaults to {@link HttpsURLConnection#getDefaultHostnameVerifier()}
*/
private HostnameVerifier hostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
/**
* Properties file that can contains key/trust info for Client Side Certificates
*/
private Properties sslConfiguration = new Properties();
public HttpsURLConnectionFactory() {}
private Properties sslConfiguration = new Properties();
public HttpsURLConnectionFactory() {
}
public HttpsURLConnectionFactory(final HostnameVerifier verifier, final Properties config) {
setHostnameVerifier(verifier);
setSSLConfiguration(config);
}
public final void setSSLConfiguration(final Properties config) {
this.sslConfiguration = config;
}
/**
* Set the host name verifier for the https connection received.
*
@ -67,7 +62,7 @@ public final class HttpsURLConnectionFactory implements HttpURLConnectionFactory
public HttpURLConnection buildHttpURLConnection(final URLConnection url) {
return this.configureHttpsConnectionIfNeeded(url);
}
/**
* Configures the connection with specific settings for secure http connections
* If the connection instance is not a {@link HttpsURLConnection},
@ -81,7 +76,7 @@ public final class HttpsURLConnectionFactory implements HttpURLConnectionFactory
final SSLSocketFactory socketFactory = this.createSSLSocketFactory();
if (socketFactory != null) {
httpsConnection.setSSLSocketFactory(socketFactory);
}
}
if (this.hostnameVerifier != null) {
httpsConnection.setHostnameVerifier(this.hostnameVerifier);
@ -89,7 +84,7 @@ public final class HttpsURLConnectionFactory implements HttpURLConnectionFactory
}
return (HttpURLConnection) conn;
}
/**
* Creates a {@link SSLSocketFactory} based on the configuration specified
* <p>
@ -115,8 +110,10 @@ public final class HttpsURLConnectionFactory implements HttpURLConnectionFactory
if (this.sslConfiguration.getProperty("keyStorePass") != null) {
keyStore.load(keyStoreIS, this.sslConfiguration.getProperty("keyStorePass").toCharArray());
LOGGER.debug("Keystore has {} keys", keyStore.size());
final KeyManagerFactory keyManager = KeyManagerFactory.getInstance(this.sslConfiguration.getProperty("keyManagerType", "SunX509"));
keyManager.init(keyStore, this.sslConfiguration.getProperty("certificatePassword").toCharArray());
final KeyManagerFactory keyManager = KeyManagerFactory.getInstance(this.sslConfiguration
.getProperty("keyManagerType", "SunX509"));
keyManager.init(keyStore, this.sslConfiguration.getProperty("certificatePassword")
.toCharArray());
sslContext.init(keyManager.getKeyManagers(), null, null);
return sslContext.getSocketFactory();
}

View File

@ -20,7 +20,6 @@
package org.jasig.cas.client.ssl;
import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
@ -37,8 +36,7 @@ public final class RegexHostnameVerifier implements HostnameVerifier {
/** Allowed hostname pattern */
private Pattern pattern;
/**
* Creates a new instance using the given regular expression.
*
@ -47,6 +45,7 @@ public final class RegexHostnameVerifier implements HostnameVerifier {
public RegexHostnameVerifier(final String regex) {
this.pattern = Pattern.compile(regex);
}
/** {@inheritDoc} */
public boolean verify(final String hostname, final SSLSession session) {
return pattern.matcher(hostname).matches();

View File

@ -33,6 +33,7 @@ public final class WhitelistHostnameVerifier implements HostnameVerifier {
/** Allowed hosts */
private String[] allowedHosts;
/**
* Creates a new instance using the given array of allowed hosts.
*
@ -41,6 +42,7 @@ public final class WhitelistHostnameVerifier implements HostnameVerifier {
public WhitelistHostnameVerifier(final String[] allowed) {
this.allowedHosts = allowed;
}
/**
* Creates a new instance using the given list of allowed hosts.
*

View File

@ -18,9 +18,6 @@
*/
package org.jasig.cas.client.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@ -50,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;
@ -96,8 +93,10 @@ public abstract class AbstractCasFilter extends AbstractConfigurationFilter {
public void init() {
CommonUtils.assertNotNull(this.artifactParameterName, "artifactParameterName cannot be null.");
CommonUtils.assertNotNull(this.serviceParameterName, "serviceParameterName cannot be null.");
CommonUtils.assertTrue(CommonUtils.isNotEmpty(this.serverName) || CommonUtils.isNotEmpty(this.service), "serverName or service must be set.");
CommonUtils.assertTrue(CommonUtils.isBlank(this.serverName) || CommonUtils.isBlank(this.service), "serverName and service cannot both be set. You MUST ONLY set one.");
CommonUtils.assertTrue(CommonUtils.isNotEmpty(this.serverName) || CommonUtils.isNotEmpty(this.service),
"serverName or service must be set.");
CommonUtils.assertTrue(CommonUtils.isBlank(this.serverName) || CommonUtils.isBlank(this.service),
"serverName and service cannot both be set. You MUST ONLY set one.");
}
// empty implementation as most filters won't need this.
@ -106,7 +105,8 @@ public abstract class AbstractCasFilter extends AbstractConfigurationFilter {
}
protected final String constructServiceUrl(final HttpServletRequest request, final HttpServletResponse response) {
return CommonUtils.constructServiceUrl(request, response, this.service, this.serverName, this.artifactParameterName, this.encodeServiceUrl);
return CommonUtils.constructServiceUrl(request, response, this.service, this.serverName,
this.artifactParameterName, this.encodeServiceUrl);
}
/**
@ -117,7 +117,7 @@ public abstract class AbstractCasFilter extends AbstractConfigurationFilter {
*/
public final void setServerName(final String serverName) {
if (serverName != null && serverName.endsWith("/")) {
this.serverName = serverName.substring(0, serverName.length()-1);
this.serverName = serverName.substring(0, serverName.length() - 1);
logger.info("Eliminated extra slash from serverName [{}]. It is now [{}]", serverName, this.serverName);
} else {
this.serverName = serverName;
@ -135,9 +135,9 @@ public abstract class AbstractCasFilter extends AbstractConfigurationFilter {
public final void setServiceParameterName(final String serviceParameterName) {
this.serviceParameterName = serviceParameterName;
}
public final void setEncodeServiceUrl(final boolean encodeServiceUrl) {
this.encodeServiceUrl = encodeServiceUrl;
this.encodeServiceUrl = encodeServiceUrl;
}
public final String getArtifactParameterName() {
@ -155,6 +155,6 @@ public abstract class AbstractCasFilter extends AbstractConfigurationFilter {
* @return the ticket if its found, null otherwise.
*/
protected String retrieveTicketFromRequest(final HttpServletRequest request) {
return CommonUtils.safeGetParameter(request,getArtifactParameterName());
return CommonUtils.safeGetParameter(request, getArtifactParameterName());
}
}

View File

@ -22,7 +22,6 @@ import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -34,8 +33,8 @@ import org.slf4j.LoggerFactory;
* @since 3.1
*/
public abstract class AbstractConfigurationFilter implements Filter {
protected final Logger logger = LoggerFactory.getLogger(getClass());
protected final Logger logger = LoggerFactory.getLogger(getClass());
private boolean ignoreInitConfiguration = false;
@ -63,7 +62,8 @@ public abstract class AbstractConfigurationFilter implements Filter {
* @return the property value, following the above conventions. It will always return the more specific value (i.e.
* filter vs. context).
*/
protected final String getPropertyFromInitParams(final FilterConfig filterConfig, final String propertyName, final String defaultValue) {
protected final String getPropertyFromInitParams(final FilterConfig filterConfig, final String propertyName,
final String defaultValue) {
final String value = filterConfig.getInitParameter(propertyName);
if (CommonUtils.isNotBlank(value)) {
@ -78,47 +78,47 @@ public abstract class AbstractConfigurationFilter implements Filter {
final String value2 = filterConfig.getServletContext().getInitParameter(propertyName);
if (CommonUtils.isNotBlank(value2)) {
logger.info("Property [{}] loaded from ServletContext.getInitParameter with value [{}]", propertyName, value2);
logger.info("Property [{}] loaded from ServletContext.getInitParameter with value [{}]", propertyName,
value2);
return value2;
}
InitialContext context;
try {
context = new InitialContext();
context = new InitialContext();
} catch (final NamingException e) {
logger.warn(e.getMessage(), e);
return defaultValue;
logger.warn(e.getMessage(), e);
return defaultValue;
}
final String shortName = this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".")+1);
final String shortName = this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".") + 1);
final String value3 = loadFromContext(context, "java:comp/env/cas/" + shortName + "/" + propertyName);
if (CommonUtils.isNotBlank(value3)) {
logger.info("Property [{}] loaded from JNDI Filter Specific Property with value [{}]", propertyName, value3);
return value3;
return value3;
}
final String value4 = loadFromContext(context, "java:comp/env/cas/" + propertyName);
final String value4 = loadFromContext(context, "java:comp/env/cas/" + propertyName);
if (CommonUtils.isNotBlank(value4)) {
logger.info("Property [{}] loaded from JNDI with value [{}]", propertyName, value4);
return value4;
return value4;
}
logger.info("Property [{}] not found. Using default value [{}]", propertyName, defaultValue);
return defaultValue;
}
protected final boolean parseBoolean(final String value) {
return ((value != null) && value.equalsIgnoreCase("true"));
return ((value != null) && value.equalsIgnoreCase("true"));
}
protected final String loadFromContext(final InitialContext context, final String path) {
try {
return (String) context.lookup(path);
} catch (final NamingException e) {
return null;
}
try {
return (String) context.lookup(path);
} catch (final NamingException e) {
return null;
}
}
public final void setIgnoreInitConfiguration(boolean ignoreInitConfiguration) {

View File

@ -33,6 +33,7 @@ public class AssertionHolder {
* ThreadLocal to hold the Assertion for Threads to access.
*/
private static final ThreadLocal<Assertion> threadLocal = new ThreadLocal<Assertion>();
/**
* Retrieve the assertion from the ThreadLocal.
*

View File

@ -18,17 +18,11 @@
*/
package org.jasig.cas.client.util;
import org.jasig.cas.client.validation.Assertion;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import org.jasig.cas.client.validation.Assertion;
/**
* Places the assertion in a ThreadLocal such that other resources can access it that do not have access to the web tier session.
@ -43,10 +37,13 @@ public final class AssertionThreadLocalFilter implements Filter {
// nothing to do here
}
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
final FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpSession session = request.getSession(false);
final Assertion assertion = (Assertion) (session == null ? request.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION) : session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION));
final Assertion assertion = (Assertion) (session == null ? request
.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION) : session
.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION));
try {
AssertionHolder.setAssertion(assertion);

View File

@ -18,32 +18,22 @@
*/
package org.jasig.cas.client.util;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage;
import org.jasig.cas.client.ssl.HttpsURLConnectionFactory;
import org.jasig.cas.client.ssl.HttpURLConnectionFactory;
import org.jasig.cas.client.validation.ProxyList;
import org.jasig.cas.client.validation.ProxyListEditor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Closeable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.URL;
import java.net.HttpURLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Common utilities so that we don't need to include Commons Lang.
*
@ -54,7 +44,7 @@ import java.util.*;
public final class CommonUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(CommonUtils.class);
/**
* Constant representing the ProxyGrantingTicket IOU Request Parameter.
*/
@ -168,35 +158,39 @@ public final class CommonUtils {
* @param gateway where we should send gateway or not.
* @return the fully constructed redirect url.
*/
public static String constructRedirectUrl(final String casServerLoginUrl, final String serviceParameterName, final String serviceUrl, final boolean renew, final boolean gateway) {
public static String constructRedirectUrl(final String casServerLoginUrl, final String serviceParameterName,
final String serviceUrl, final boolean renew, final boolean gateway) {
try {
return casServerLoginUrl + (casServerLoginUrl.contains("?") ? "&" : "?") + serviceParameterName + "="
+ URLEncoder.encode(serviceUrl, "UTF-8")
+ (renew ? "&renew=true" : "")
+ URLEncoder.encode(serviceUrl, "UTF-8") + (renew ? "&renew=true" : "")
+ (gateway ? "&gateway=true" : "");
} catch (final UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static void readAndRespondToProxyReceptorRequest(final HttpServletRequest request, final HttpServletResponse response, final ProxyGrantingTicketStorage proxyGrantingTicketStorage) throws IOException {
public static void readAndRespondToProxyReceptorRequest(final HttpServletRequest request,
final HttpServletResponse response, final ProxyGrantingTicketStorage proxyGrantingTicketStorage)
throws IOException {
final String proxyGrantingTicketIou = request.getParameter(PARAM_PROXY_GRANTING_TICKET_IOU);
final String proxyGrantingTicket = request.getParameter(PARAM_PROXY_GRANTING_TICKET);
final String proxyGrantingTicket = request.getParameter(PARAM_PROXY_GRANTING_TICKET);
if (CommonUtils.isBlank(proxyGrantingTicket) || CommonUtils.isBlank(proxyGrantingTicketIou)) {
response.getWriter().write("");
return;
}
if (CommonUtils.isBlank(proxyGrantingTicket) || CommonUtils.isBlank(proxyGrantingTicketIou)) {
response.getWriter().write("");
return;
}
LOGGER.debug("Received proxyGrantingTicketId [{}] for proxyGrantingTicketIou [{}]", proxyGrantingTicket, proxyGrantingTicketIou);
LOGGER.debug("Received proxyGrantingTicketId [{}] for proxyGrantingTicketIou [{}]", proxyGrantingTicket,
proxyGrantingTicketIou);
proxyGrantingTicketStorage.save(proxyGrantingTicketIou, proxyGrantingTicket);
proxyGrantingTicketStorage.save(proxyGrantingTicketIou, proxyGrantingTicket);
LOGGER.debug("Successfully saved proxyGrantingTicketId [{}] for proxyGrantingTicketIou [{}]", proxyGrantingTicket, proxyGrantingTicketIou);
LOGGER.debug("Successfully saved proxyGrantingTicketId [{}] for proxyGrantingTicketIou [{}]",
proxyGrantingTicket, proxyGrantingTicketIou);
response.getWriter().write("<?xml version=\"1.0\"?>");
response.getWriter().write("<casClient:proxySuccess xmlns:casClient=\"http://www.yale.edu/tp/casClient\" />");
response.getWriter().write("<?xml version=\"1.0\"?>");
response.getWriter().write("<casClient:proxySuccess xmlns:casClient=\"http://www.yale.edu/tp/casClient\" />");
}
protected static String findMatchingServerName(final HttpServletRequest request, final String serverName) {
@ -208,12 +202,12 @@ public final class CommonUtils {
final String host = request.getHeader("Host");
final String xHost = request.getHeader("X-Forwarded-Host");
final String comparisonHost;
if (xHost != null && host == "localhost") {
comparisonHost = xHost;
comparisonHost = xHost;
} else {
comparisonHost = host;
comparisonHost = host;
}
if (comparisonHost == null) {
@ -230,23 +224,24 @@ public final class CommonUtils {
return serverNames[0];
}
/**
* Constructs a service url from the HttpServletRequest or from the given
* serviceUrl. Prefers the serviceUrl provided if both a serviceUrl and a
* serviceName.
*
* @param request the HttpServletRequest
* @param response the HttpServletResponse
* @param service the configured service url (this will be used if not null)
* @param serverNames the server name to use to constuct the service url if the service param is empty. Note, prior to CAS Client 3.3, this was a single value.
* As of 3.3, it can be a space-separated value. We keep it as a single value, but will convert it to an array internally to get the matching value. This keeps backward compatability with anything using this public
* method.
* @param artifactParameterName the artifact parameter name to remove (i.e. ticket)
* @param encode whether to encode the url or not (i.e. Jsession).
* @return the service url to use.
*/
public static String constructServiceUrl(final HttpServletRequest request, final HttpServletResponse response, final String service, final String serverNames, final String artifactParameterName, final boolean encode) {
/**
* Constructs a service url from the HttpServletRequest or from the given
* serviceUrl. Prefers the serviceUrl provided if both a serviceUrl and a
* serviceName.
*
* @param request the HttpServletRequest
* @param response the HttpServletResponse
* @param service the configured service url (this will be used if not null)
* @param serverNames the server name to use to constuct the service url if the service param is empty. Note, prior to CAS Client 3.3, this was a single value.
* As of 3.3, it can be a space-separated value. We keep it as a single value, but will convert it to an array internally to get the matching value. This keeps backward compatability with anything using this public
* method.
* @param artifactParameterName the artifact parameter name to remove (i.e. ticket)
* @param encode whether to encode the url or not (i.e. Jsession).
* @return the service url to use.
*/
public static String constructServiceUrl(final HttpServletRequest request, final HttpServletResponse response,
final String service, final String serverNames, final String artifactParameterName, final boolean encode) {
if (CommonUtils.isNotBlank(service)) {
return encode ? response.encodeURL(service) : service;
}
@ -266,7 +261,7 @@ public final class CommonUtils {
final int location = request.getQueryString().indexOf(artifactParameterName + "=");
if (location == 0) {
final String returnValue = encode ? response.encodeURL(buffer.toString()): buffer.toString();
final String returnValue = encode ? response.encodeURL(buffer.toString()) : buffer.toString();
LOGGER.debug("serviceUrl generated: {}", returnValue);
return returnValue;
}
@ -276,14 +271,12 @@ public final class CommonUtils {
if (location == -1) {
buffer.append(request.getQueryString());
} else if (location > 0) {
final int actualLocation = request.getQueryString()
.indexOf("&" + artifactParameterName + "=");
final int actualLocation = request.getQueryString().indexOf("&" + artifactParameterName + "=");
if (actualLocation == -1) {
buffer.append(request.getQueryString());
} else if (actualLocation > 0) {
buffer.append(request.getQueryString().substring(0,
actualLocation));
buffer.append(request.getQueryString().substring(0, actualLocation));
}
}
}
@ -309,12 +302,14 @@ public final class CommonUtils {
* @param parameter the parameter to look for.
* @return the value of the parameter.
*/
public static String safeGetParameter(final HttpServletRequest request, final String parameter, final List<String> parameters) {
public static String safeGetParameter(final HttpServletRequest request, final String parameter,
final List<String> parameters) {
if ("POST".equals(request.getMethod()) && parameters.contains(parameter)) {
LOGGER.debug("safeGetParameter called on a POST HttpServletRequest for Restricted Parameters. Cannot complete check safely. Reverting to standard behavior for this Parameter");
return request.getParameter(parameter);
}
return request.getQueryString() == null || !request.getQueryString().contains(parameter) ? null : request.getParameter(parameter);
return request.getQueryString() == null || !request.getQueryString().contains(parameter) ? null : request
.getParameter(parameter);
}
public static String safeGetParameter(final HttpServletRequest request, final String parameter) {
@ -329,12 +324,13 @@ public final class CommonUtils {
* @param encoding the encoding to use.
* @return the response.
*/
public static String getResponseFromServer(final URL constructedUrl, final HttpURLConnectionFactory factory, final String encoding) {
public static String getResponseFromServer(final URL constructedUrl, final HttpURLConnectionFactory factory,
final String encoding) {
HttpURLConnection conn = null;
try {
conn = factory.buildHttpURLConnection(constructedUrl.openConnection());
final BufferedReader in;
if (CommonUtils.isEmpty(encoding)) {
@ -360,7 +356,7 @@ public final class CommonUtils {
}
}
}
public static ProxyList createProxyList(final String proxies) {
if (CommonUtils.isBlank(proxies)) {
return new ProxyList();
@ -369,7 +365,7 @@ public final class CommonUtils {
final ProxyListEditor editor = new ProxyListEditor();
editor.setAsText(proxies);
return (ProxyList) editor.getValue();
}
}
/**
* Sends the redirect message and captures the exceptions that we can't possibly do anything with.

View File

@ -18,18 +18,12 @@
*/
package org.jasig.cas.client.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A Delegating Filter looks up a parameter in the request object and matches
@ -55,7 +49,7 @@ public final class DelegatingFilter implements Filter {
/**
* The map of filters to delegate to and the criteria (as key).
*/
private final Map<String,Filter> delegators;
private final Map<String, Filter> delegators;
/**
* The default filter to use if there is no match.
@ -68,11 +62,13 @@ public final class DelegatingFilter implements Filter {
*/
private final boolean exactMatch;
public DelegatingFilter(final String requestParameterName, final Map<String,Filter> delegators, final boolean exactMatch) {
public DelegatingFilter(final String requestParameterName, final Map<String, Filter> delegators,
final boolean exactMatch) {
this(requestParameterName, delegators, exactMatch, null);
}
public DelegatingFilter(final String requestParameterName, final Map<String,Filter> delegators, final boolean exactMatch, final Filter defaultFilter) {
public DelegatingFilter(final String requestParameterName, final Map<String, Filter> delegators,
final boolean exactMatch, final Filter defaultFilter) {
CommonUtils.assertNotNull(requestParameterName, "requestParameterName cannot be null.");
CommonUtils.assertTrue(!delegators.isEmpty(), "delegators cannot be empty.");
@ -86,7 +82,8 @@ public final class DelegatingFilter implements Filter {
// nothing to do here
}
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException {
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain)
throws IOException, ServletException {
final String parameter = CommonUtils.safeGetParameter((HttpServletRequest) request, this.requestParameterName);
@ -94,14 +91,15 @@ public final class DelegatingFilter implements Filter {
for (final String key : this.delegators.keySet()) {
if ((parameter.equals(key) && this.exactMatch) || (parameter.matches(key) && !this.exactMatch)) {
final Filter filter = this.delegators.get(key);
logger.debug("Match found for parameter [{}] with value [{}]. Delegating to filter [{}]", this.requestParameterName, parameter, filter.getClass().getName());
logger.debug("Match found for parameter [{}] with value [{}]. Delegating to filter [{}]",
this.requestParameterName, parameter, filter.getClass().getName());
filter.doFilter(request, response, filterChain);
return;
}
}
}
logger.debug("No match found for parameter [{}] with value [{}]", this.requestParameterName , parameter);
logger.debug("No match found for parameter [{}] with value [{}]", this.requestParameterName, parameter);
if (this.defaultFilter != null) {
this.defaultFilter.doFilter(request, response, filterChain);

View File

@ -22,15 +22,8 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -50,78 +43,78 @@ import org.slf4j.LoggerFactory;
*/
public final class ErrorRedirectFilter implements Filter {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final List<ErrorHolder> errors = new ArrayList<ErrorHolder>();
private String defaultErrorRedirectPage;
public void destroy() {
// nothing to do here
}
private final Logger logger = LoggerFactory.getLogger(getClass());
public void doFilter(final ServletRequest request, final ServletResponse response,
final FilterChain filterChain) throws IOException, ServletException {
final HttpServletResponse httpResponse = (HttpServletResponse) response;
try {
filterChain.doFilter(request, response);
} catch (final ServletException e) {
final Throwable t = e.getCause();
ErrorHolder currentMatch = null;
private final List<ErrorHolder> errors = new ArrayList<ErrorHolder>();
private String defaultErrorRedirectPage;
public void destroy() {
// nothing to do here
}
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain)
throws IOException, ServletException {
final HttpServletResponse httpResponse = (HttpServletResponse) response;
try {
filterChain.doFilter(request, response);
} catch (final ServletException e) {
final Throwable t = e.getCause();
ErrorHolder currentMatch = null;
for (final ErrorHolder errorHolder : this.errors) {
if (errorHolder.exactMatch(t)) {
currentMatch = errorHolder;
break;
} else if (errorHolder.inheritanceMatch(t)) {
currentMatch = errorHolder;
}
}
if (currentMatch != null) {
httpResponse.sendRedirect(currentMatch.getUrl());
} else {
httpResponse.sendRedirect(defaultErrorRedirectPage);
}
}
}
if (errorHolder.exactMatch(t)) {
currentMatch = errorHolder;
break;
} else if (errorHolder.inheritanceMatch(t)) {
currentMatch = errorHolder;
}
}
public void init(final FilterConfig filterConfig) throws ServletException {
this.defaultErrorRedirectPage = filterConfig.getInitParameter("defaultErrorRedirectPage");
final Enumeration<?> enumeration = filterConfig.getInitParameterNames();
while (enumeration.hasMoreElements()) {
final String className = (String) enumeration.nextElement();
try {
if (!className.equals("defaultErrorRedirectPage")) {
this.errors.add(new ErrorHolder(className, filterConfig.getInitParameter(className)));
}
} catch (final ClassNotFoundException e) {
logger.warn("Class [{}] cannot be found in ClassLoader. Ignoring.", className);
}
}
}
protected final class ErrorHolder {
private Class<?> className;
private String url;
protected ErrorHolder(final String className, final String url) throws ClassNotFoundException {
this.className = Class.forName(className);
this.url = url;
}
public boolean exactMatch(final Throwable e) {
return this.className.equals(e.getClass());
}
public boolean inheritanceMatch(final Throwable e) {
return className.isAssignableFrom(e.getClass());
}
public String getUrl() {
return this.url;
}
}
if (currentMatch != null) {
httpResponse.sendRedirect(currentMatch.getUrl());
} else {
httpResponse.sendRedirect(defaultErrorRedirectPage);
}
}
}
public void init(final FilterConfig filterConfig) throws ServletException {
this.defaultErrorRedirectPage = filterConfig.getInitParameter("defaultErrorRedirectPage");
final Enumeration<?> enumeration = filterConfig.getInitParameterNames();
while (enumeration.hasMoreElements()) {
final String className = (String) enumeration.nextElement();
try {
if (!className.equals("defaultErrorRedirectPage")) {
this.errors.add(new ErrorHolder(className, filterConfig.getInitParameter(className)));
}
} catch (final ClassNotFoundException e) {
logger.warn("Class [{}] cannot be found in ClassLoader. Ignoring.", className);
}
}
}
protected final class ErrorHolder {
private Class<?> className;
private String url;
protected ErrorHolder(final String className, final String url) throws ClassNotFoundException {
this.className = Class.forName(className);
this.url = url;
}
public boolean exactMatch(final Throwable e) {
return this.className.equals(e.getClass());
}
public boolean inheritanceMatch(final Throwable e) {
return className.isAssignableFrom(e.getClass());
}
public String getUrl() {
return this.url;
}
}
}

View File

@ -18,20 +18,15 @@
*/
package org.jasig.cas.client.util;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.Assertion;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.Principal;
import java.util.Collection;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.Assertion;
/**
* Implementation of a filter that wraps the normal HttpServletRequest with a
@ -55,7 +50,7 @@ public final class HttpServletRequestWrapperFilter extends AbstractConfiguration
/** Name of the attribute used to answer role membership queries */
private String roleAttribute;
/** Whether or not to ignore case in role membership queries */
private boolean ignoreCase;
@ -68,16 +63,20 @@ public final class HttpServletRequestWrapperFilter extends AbstractConfiguration
* <code>request.getRemoteUser</code> to the underlying Assertion object
* stored in the user session.
*/
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
final FilterChain filterChain) throws IOException, ServletException {
final AttributePrincipal principal = retrievePrincipalFromSessionOrRequest(servletRequest);
filterChain.doFilter(new CasHttpServletRequestWrapper((HttpServletRequest) servletRequest, principal), servletResponse);
filterChain.doFilter(new CasHttpServletRequestWrapper((HttpServletRequest) servletRequest, principal),
servletResponse);
}
protected AttributePrincipal retrievePrincipalFromSessionOrRequest(final ServletRequest servletRequest) {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpSession session = request.getSession(false);
final Assertion assertion = (Assertion) (session == null ? request.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION) : session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION));
final Assertion assertion = (Assertion) (session == null ? request
.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION) : session
.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION));
return assertion == null ? null : assertion.getPrincipal();
}
@ -121,7 +120,7 @@ public final class HttpServletRequestWrapperFilter extends AbstractConfiguration
}
final Object value = this.principal.getAttributes().get(roleAttribute);
if (value instanceof Collection<?>) {
for (final Object o : (Collection<?>) value) {
if (rolesEqual(role, o)) {
@ -135,7 +134,7 @@ public final class HttpServletRequestWrapperFilter extends AbstractConfiguration
logger.debug("User [{}] is in role [{}]: {}", getRemoteUser(), role, isMember);
return isMember;
}
/**
* Determines whether the given role is equal to the candidate
* role attribute taking into account case sensitivity.

View File

@ -52,6 +52,7 @@ public final class ReflectUtils {
throw new IllegalArgumentException(className + " class not found.");
}
}
/**
* Creates a new instance of the given class by passing the given arguments
* to the constructor.
@ -59,10 +60,10 @@ public final class ReflectUtils {
* @param args Constructor arguments.
* @return New instance of given class.
*/
public static <T> T newInstance(final String className, final Object ... args) {
return newInstance(ReflectUtils.<T>loadClass(className), args);
public static <T> T newInstance(final String className, final Object... args) {
return newInstance(ReflectUtils.<T> loadClass(className), args);
}
/**
* Creates a new instance of the given class by passing the given arguments
* to the constructor.
@ -70,7 +71,7 @@ public final class ReflectUtils {
* @param args Constructor arguments.
* @return New instance of given class.
*/
public static <T> T newInstance(final Class<T> clazz, final Object ... args) {
public static <T> T newInstance(final Class<T> clazz, final Object... args) {
final Class<?>[] argClasses = new Class[args.length];
for (int i = 0; i < args.length; i++) {
argClasses[i] = args[i].getClass();
@ -136,7 +137,8 @@ public final class ReflectUtils {
* @param target Target JavaBean on which to set property.
* @param info BeanInfo describing the target JavaBean.
*/
public static void setProperty(final String propertyName, final Object value, final Object target, final BeanInfo info) {
public static void setProperty(final String propertyName, final Object value, final Object target,
final BeanInfo info) {
try {
final PropertyDescriptor pd = getPropertyDescriptor(info, propertyName);
pd.getWriteMethod().invoke(target, value);

View File

@ -18,10 +18,11 @@
*/
package org.jasig.cas.client.util;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
@ -29,14 +30,6 @@ import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
/**
* Common utilities for easily parsing XML without duplicating logic.
*
@ -75,8 +68,7 @@ public final class XmlUtils {
* @param element the element to look for
* @return the list of text from the elements.
*/
public static List<String> getTextForElements(final String xmlAsString,
final String element) {
public static List<String> getTextForElements(final String xmlAsString, final String element) {
final List<String> elements = new ArrayList<String>(2);
final XMLReader reader = getXmlReader();
@ -86,16 +78,14 @@ public final class XmlUtils {
private StringBuilder buffer = new StringBuilder();
public void startElement(final String uri, final String localName,
final String qName, final Attributes attributes)
throws SAXException {
public void startElement(final String uri, final String localName, final String qName,
final Attributes attributes) throws SAXException {
if (localName.equals(element)) {
this.foundElement = true;
}
}
public void endElement(final String uri, final String localName,
final String qName) throws SAXException {
public void endElement(final String uri, final String localName, final String qName) throws SAXException {
if (localName.equals(element)) {
this.foundElement = false;
elements.add(this.buffer.toString());
@ -103,8 +93,7 @@ public final class XmlUtils {
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
public void characters(char[] ch, int start, int length) throws SAXException {
if (this.foundElement) {
this.buffer.append(ch, start, length);
}
@ -132,8 +121,7 @@ public final class XmlUtils {
* @param element the element to look for
* @return the text value of the element.
*/
public static String getTextForElement(final String xmlAsString,
final String element) {
public static String getTextForElement(final String xmlAsString, final String element) {
final XMLReader reader = getXmlReader();
final StringBuilder builder = new StringBuilder();
@ -141,23 +129,20 @@ public final class XmlUtils {
private boolean foundElement = false;
public void startElement(final String uri, final String localName,
final String qName, final Attributes attributes)
throws SAXException {
public void startElement(final String uri, final String localName, final String qName,
final Attributes attributes) throws SAXException {
if (localName.equals(element)) {
this.foundElement = true;
}
}
public void endElement(final String uri, final String localName,
final String qName) throws SAXException {
public void endElement(final String uri, final String localName, final String qName) throws SAXException {
if (localName.equals(element)) {
this.foundElement = false;
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
public void characters(char[] ch, int start, int length) throws SAXException {
if (this.foundElement) {
builder.append(ch, start, length);
}

View File

@ -18,9 +18,8 @@
*/
package org.jasig.cas.client.validation;
import org.jasig.cas.client.util.CommonUtils;
import java.net.URL;
import org.jasig.cas.client.util.CommonUtils;
/**
* Abstract class that knows the protocol for validating a CAS ticket.

View File

@ -18,22 +18,17 @@
*/
package org.jasig.cas.client.validation;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import javax.net.ssl.HostnameVerifier;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.util.ReflectUtils;
import javax.net.ssl.HostnameVerifier;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.Properties;
/**
* The filter that handles all the work of validating ticket requests.
* <p>
@ -91,15 +86,15 @@ public abstract class AbstractTicketValidationFilter extends AbstractCasFilter {
*/
protected Properties getSSLConfig(final FilterConfig filterConfig) {
final Properties properties = new Properties();
final String fileName = getPropertyFromInitParams(filterConfig, "sslConfigFile", null);
final String fileName = getPropertyFromInitParams(filterConfig, "sslConfigFile", null);
if (fileName != null) {
FileInputStream fis = null;
try {
fis = new FileInputStream(fileName);
properties.load(fis);
logger.trace("Loaded {} entries from {}", properties.size(), fileName);
} catch(final IOException ioe) {
logger.trace("Loaded {} entries from {}", properties.size(), fileName);
} catch (final IOException ioe) {
logger.error(ioe.getMessage(), ioe);
} finally {
CommonUtils.closeQuietly(fis);
@ -130,9 +125,11 @@ public abstract class AbstractTicketValidationFilter extends AbstractCasFilter {
}
protected void initInternal(final FilterConfig filterConfig) throws ServletException {
setExceptionOnValidationFailure(parseBoolean(getPropertyFromInitParams(filterConfig, "exceptionOnValidationFailure", "true")));
setExceptionOnValidationFailure(parseBoolean(getPropertyFromInitParams(filterConfig,
"exceptionOnValidationFailure", "true")));
logger.trace("Setting exceptionOnValidationFailure parameter: {}", this.exceptionOnValidationFailure);
setRedirectAfterValidation(parseBoolean(getPropertyFromInitParams(filterConfig, "redirectAfterValidation", "true")));
setRedirectAfterValidation(parseBoolean(getPropertyFromInitParams(filterConfig, "redirectAfterValidation",
"true")));
logger.trace("Setting redirectAfterValidation parameter: {}", this.redirectAfterValidation);
setUseSession(parseBoolean(getPropertyFromInitParams(filterConfig, "useSession", "true")));
logger.trace("Setting useSession parameter: {}", this.useSession);
@ -161,7 +158,8 @@ public abstract class AbstractTicketValidationFilter extends AbstractCasFilter {
* @throws IOException if there is an I/O problem
* @throws ServletException if there is a servlet problem.
*/
protected boolean preFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
protected boolean preFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
final FilterChain filterChain) throws IOException, ServletException {
return true;
}
@ -174,7 +172,8 @@ public abstract class AbstractTicketValidationFilter extends AbstractCasFilter {
* @param response the HttpServletResponse.
* @param assertion the successful Assertion from the server.
*/
protected void onSuccessfulValidation(final HttpServletRequest request, final HttpServletResponse response, final Assertion assertion) {
protected void onSuccessfulValidation(final HttpServletRequest request, final HttpServletResponse response,
final Assertion assertion) {
// nothing to do here.
}
@ -189,7 +188,8 @@ public abstract class AbstractTicketValidationFilter extends AbstractCasFilter {
// nothing to do here.
}
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
final FilterChain filterChain) throws IOException, ServletException {
if (!preFilter(servletRequest, servletResponse, filterChain)) {
return;
@ -203,7 +203,8 @@ public abstract class AbstractTicketValidationFilter extends AbstractCasFilter {
logger.debug("Attempting to validate ticket: {}", ticket);
try {
final Assertion assertion = this.ticketValidator.validate(ticket, constructServiceUrl(request, response));
final Assertion assertion = this.ticketValidator.validate(ticket,
constructServiceUrl(request, response));
logger.debug("Successfully authenticated user: {}", assertion.getPrincipal().getName());
@ -215,7 +216,7 @@ public abstract class AbstractTicketValidationFilter extends AbstractCasFilter {
onSuccessfulValidation(request, response, assertion);
if (this.redirectAfterValidation) {
logger. debug("Redirecting after successful ticket validation.");
logger.debug("Redirecting after successful ticket validation.");
response.sendRedirect(constructServiceUrl(request, response));
return;
}
@ -240,8 +241,8 @@ public abstract class AbstractTicketValidationFilter extends AbstractCasFilter {
}
public final void setTicketValidator(final TicketValidator ticketValidator) {
this.ticketValidator = ticketValidator;
}
this.ticketValidator = ticketValidator;
}
public final void setRedirectAfterValidation(final boolean redirectAfterValidation) {
this.redirectAfterValidation = redirectAfterValidation;

View File

@ -18,18 +18,17 @@
*/
package org.jasig.cas.client.validation;
import org.jasig.cas.client.ssl.HttpsURLConnectionFactory;
import org.jasig.cas.client.ssl.HttpURLConnectionFactory;
import org.jasig.cas.client.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import org.jasig.cas.client.ssl.HttpURLConnectionFactory;
import org.jasig.cas.client.ssl.HttpsURLConnectionFactory;
import org.jasig.cas.client.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract validator implementation for tickets that must be validated against a server.
@ -40,13 +39,13 @@ import java.util.Map;
public abstract class AbstractUrlBasedTicketValidator implements TicketValidator {
protected final Logger logger = LoggerFactory.getLogger(getClass());
/**
* URLConnection factory instance to use when making validation requests to the CAS server.
* Defaults to {@link HttpsURLConnectionFactory}
*/
private HttpURLConnectionFactory urlConnectionFactory = new HttpsURLConnectionFactory();
/**
* Prefix for the CAS server. Should be everything up to the url endpoint, including the /.
*
@ -62,7 +61,7 @@ public abstract class AbstractUrlBasedTicketValidator implements TicketValidator
/**
* A map containing custom parameters to pass to the validation url.
*/
private Map<String,String> customParameters;
private Map<String, String> customParameters;
private String encoding;
@ -81,7 +80,7 @@ public abstract class AbstractUrlBasedTicketValidator implements TicketValidator
*
* @param urlParameters the map containing the parameters.
*/
protected void populateUrlAttributeMap(final Map<String,String> urlParameters) {
protected void populateUrlAttributeMap(final Map<String, String> urlParameters) {
// nothing to do
}
@ -107,7 +106,7 @@ public abstract class AbstractUrlBasedTicketValidator implements TicketValidator
* @return the fully constructed URL.
*/
protected final String constructValidationUrl(final String ticket, final String serviceUrl) {
final Map<String,String> urlParameters = new HashMap<String,String>();
final Map<String, String> urlParameters = new HashMap<String, String>();
logger.debug("Placing URL parameters in map.");
urlParameters.put("ticket", ticket);
@ -126,7 +125,8 @@ public abstract class AbstractUrlBasedTicketValidator implements TicketValidator
}
final String suffix = getUrlSuffix();
final StringBuilder buffer = new StringBuilder(urlParameters.size()*10 + this.casServerUrlPrefix.length() + suffix.length() +1);
final StringBuilder buffer = new StringBuilder(urlParameters.size() * 10 + this.casServerUrlPrefix.length()
+ suffix.length() + 1);
int i = 0;
@ -136,7 +136,7 @@ public abstract class AbstractUrlBasedTicketValidator implements TicketValidator
}
buffer.append(suffix);
for (Map.Entry<String,String> entry : urlParameters.entrySet()) {
for (Map.Entry<String, String> entry : urlParameters.entrySet()) {
final String key = entry.getKey();
final String value = entry.getValue();
@ -159,10 +159,10 @@ public abstract class AbstractUrlBasedTicketValidator implements TicketValidator
* @return the encoded url, or the original url if "UTF-8" character encoding could not be found.
*/
protected final String encodeUrl(final String url) {
if (url == null) {
return null;
}
if (url == null) {
return null;
}
try {
return URLEncoder.encode(url, "UTF-8");
} catch (final UnsupportedEncodingException e) {
@ -192,17 +192,17 @@ public abstract class AbstractUrlBasedTicketValidator implements TicketValidator
public final Assertion validate(final String ticket, final String service) throws TicketValidationException {
final String validationUrl = constructValidationUrl(ticket, service);
logger.debug("Constructing validation url: {}", validationUrl);
logger.debug("Constructing validation url: {}", validationUrl);
try {
logger.debug("Retrieving response from server.");
logger.debug("Retrieving response from server.");
final String serverResponse = retrieveResponseFromServer(new URL(validationUrl), ticket);
if (serverResponse == null) {
throw new TicketValidationException("The CAS server returned no response.");
}
logger.debug("Server response: {}", serverResponse);
logger.debug("Server response: {}", serverResponse);
return parseResponseFromServer(serverResponse);
} catch (final MalformedURLException e) {
@ -214,7 +214,7 @@ public abstract class AbstractUrlBasedTicketValidator implements TicketValidator
this.renew = renew;
}
public final void setCustomParameters(final Map<String,String> customParameters) {
public final void setCustomParameters(final Map<String, String> customParameters) {
this.customParameters = customParameters;
}
@ -241,7 +241,7 @@ public abstract class AbstractUrlBasedTicketValidator implements TicketValidator
protected HttpURLConnectionFactory getURLConnectionFactory() {
return this.urlConnectionFactory;
}
public void setURLConnectionFactory(final HttpURLConnectionFactory urlConnectionFactory) {
this.urlConnectionFactory = urlConnectionFactory;
}

View File

@ -18,11 +18,10 @@
*/
package org.jasig.cas.client.validation;
import org.jasig.cas.client.authentication.AttributePrincipal;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;
import org.jasig.cas.client.authentication.AttributePrincipal;
/**
* Represents a response to a validation request.
@ -60,7 +59,7 @@ public interface Assertion extends Serializable {
*
* @return the map of attributes.
*/
Map<String,Object> getAttributes();
Map<String, Object> getAttributes();
/**
* The principal for which this assertion is valid.

View File

@ -18,13 +18,12 @@
*/
package org.jasig.cas.client.validation;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.jasig.cas.client.util.CommonUtils;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.jasig.cas.client.util.CommonUtils;
/**
* Concrete Implementation of the {@link Assertion}.
@ -37,9 +36,9 @@ import java.util.Map;
public final class AssertionImpl implements Assertion {
/** Unique Id for serialization. */
private static final long serialVersionUID = -7767943925833639221L;
private static final long serialVersionUID = -7767943925833639221L;
/** The date from which the assertion is valid. */
/** The date from which the assertion is valid. */
private final Date validFromDate;
/** The date the assertion is valid until. */
@ -48,7 +47,7 @@ public final class AssertionImpl implements Assertion {
private final Date authenticationDate;
/** Map of key/value pairs associated with this assertion. I.e. authentication type. */
private final Map<String,Object> attributes;
private final Map<String, Object> attributes;
/** The principal for which this assertion is valid for. */
private final AttributePrincipal principal;
@ -59,7 +58,7 @@ public final class AssertionImpl implements Assertion {
* @param name the name of the principal for which this assertion is valid.
*/
public AssertionImpl(final String name) {
this(new AttributePrincipalImpl(name));
this(new AttributePrincipalImpl(name));
}
/**
@ -68,7 +67,7 @@ public final class AssertionImpl implements Assertion {
* @param principal the Principal to associate with the Assertion.
*/
public AssertionImpl(final AttributePrincipal principal) {
this(principal, Collections.<String, Object>emptyMap());
this(principal, Collections.<String, Object> emptyMap());
}
/**
@ -77,7 +76,7 @@ public final class AssertionImpl implements Assertion {
* @param principal the Principal to associate with the Assertion.
* @param attributes the key/value pairs for this attribute.
*/
public AssertionImpl(final AttributePrincipal principal, final Map<String,Object> attributes) {
public AssertionImpl(final AttributePrincipal principal, final Map<String, Object> attributes) {
this(principal, new Date(), null, new Date(), attributes);
}
@ -89,7 +88,8 @@ public final class AssertionImpl implements Assertion {
* @param validUntilDate when the assertion is valid to.
* @param attributes the key/value pairs for this attribute.
*/
public AssertionImpl(final AttributePrincipal principal, final Date validFromDate, final Date validUntilDate, final Date authenticationDate, final Map<String,Object> attributes) {
public AssertionImpl(final AttributePrincipal principal, final Date validFromDate, final Date validUntilDate,
final Date authenticationDate, final Map<String, Object> attributes) {
this.principal = principal;
this.validFromDate = validFromDate;
this.validUntilDate = validUntilDate;
@ -113,7 +113,7 @@ public final class AssertionImpl implements Assertion {
return this.validUntilDate;
}
public Map<String,Object> getAttributes() {
public Map<String, Object> getAttributes() {
return this.attributes;
}

View File

@ -19,9 +19,8 @@
package org.jasig.cas.client.validation;
import javax.servlet.FilterConfig;
import org.jasig.cas.client.ssl.HttpsURLConnectionFactory;
import org.jasig.cas.client.ssl.HttpURLConnectionFactory;
import org.jasig.cas.client.ssl.HttpsURLConnectionFactory;
/**
* Implementation of AbstractTicketValidatorFilter that instanciates a Cas10TicketValidator.
@ -38,8 +37,9 @@ public class Cas10TicketValidationFilter extends AbstractTicketValidationFilter
final String casServerUrlPrefix = getPropertyFromInitParams(filterConfig, "casServerUrlPrefix", null);
final Cas10TicketValidator validator = new Cas10TicketValidator(casServerUrlPrefix);
validator.setRenew(parseBoolean(getPropertyFromInitParams(filterConfig, "renew", "false")));
final HttpURLConnectionFactory factory = new HttpsURLConnectionFactory(getHostnameVerifier(filterConfig), getSSLConfig(filterConfig));
final HttpURLConnectionFactory factory = new HttpsURLConnectionFactory(getHostnameVerifier(filterConfig),
getSSLConfig(filterConfig));
validator.setURLConnectionFactory(factory);
validator.setEncoding(getPropertyFromInitParams(filterConfig, "encoding", null));

View File

@ -20,18 +20,12 @@ package org.jasig.cas.client.validation;
import java.io.IOException;
import java.util.*;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jasig.cas.client.proxy.*;
import org.jasig.cas.client.ssl.HttpsURLConnectionFactory;
import org.jasig.cas.client.ssl.HttpURLConnectionFactory;
import org.jasig.cas.client.ssl.HttpsURLConnectionFactory;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.util.ReflectUtils;
@ -50,7 +44,11 @@ import org.jasig.cas.client.util.ReflectUtils;
*/
public class Cas20ProxyReceivingTicketValidationFilter extends AbstractTicketValidationFilter {
private static final String[] RESERVED_INIT_PARAMS = new String[] {"proxyGrantingTicketStorageClass", "proxyReceptorUrl", "acceptAnyProxy", "allowedProxyChains", "casServerUrlPrefix", "proxyCallbackUrl", "renew", "exceptionOnValidationFailure", "redirectAfterValidation", "useSession", "serverName", "service", "artifactParameterName", "serviceParameterName", "encodeServiceUrl", "millisBetweenCleanUps", "hostnameVerifier", "encoding", "config", "ticketValidatorClass"};
private static final String[] RESERVED_INIT_PARAMS = new String[] { "proxyGrantingTicketStorageClass",
"proxyReceptorUrl", "acceptAnyProxy", "allowedProxyChains", "casServerUrlPrefix", "proxyCallbackUrl",
"renew", "exceptionOnValidationFailure", "redirectAfterValidation", "useSession", "serverName", "service",
"artifactParameterName", "serviceParameterName", "encodeServiceUrl", "millisBetweenCleanUps",
"hostnameVerifier", "encoding", "config", "ticketValidatorClass" };
private static final int DEFAULT_MILLIS_BETWEEN_CLEANUPS = 60 * 1000;
@ -64,7 +62,7 @@ public class Cas20ProxyReceivingTicketValidationFilter extends AbstractTicketVal
private TimerTask timerTask;
private int millisBetweenCleanUps;
/**
* Storage location of ProxyGrantingTickets and Proxy Ticket IOUs.
*/
@ -73,14 +71,16 @@ public class Cas20ProxyReceivingTicketValidationFilter extends AbstractTicketVal
protected void initInternal(final FilterConfig filterConfig) throws ServletException {
setProxyReceptorUrl(getPropertyFromInitParams(filterConfig, "proxyReceptorUrl", null));
final String proxyGrantingTicketStorageClass = getPropertyFromInitParams(filterConfig, "proxyGrantingTicketStorageClass", null);
final String proxyGrantingTicketStorageClass = getPropertyFromInitParams(filterConfig,
"proxyGrantingTicketStorageClass", null);
if (proxyGrantingTicketStorageClass != null) {
this.proxyGrantingTicketStorage = ReflectUtils.newInstance(proxyGrantingTicketStorageClass);
if (this.proxyGrantingTicketStorage instanceof AbstractEncryptedProxyGrantingTicketStorageImpl) {
final AbstractEncryptedProxyGrantingTicketStorageImpl p = (AbstractEncryptedProxyGrantingTicketStorageImpl) this.proxyGrantingTicketStorage;
final String cipherAlgorithm = getPropertyFromInitParams(filterConfig, "cipherAlgorithm", AbstractEncryptedProxyGrantingTicketStorageImpl.DEFAULT_ENCRYPTION_ALGORITHM);
final String cipherAlgorithm = getPropertyFromInitParams(filterConfig, "cipherAlgorithm",
AbstractEncryptedProxyGrantingTicketStorageImpl.DEFAULT_ENCRYPTION_ALGORITHM);
final String secretKey = getPropertyFromInitParams(filterConfig, "secretKey", null);
p.setCipherAlgorithm(cipherAlgorithm);
@ -96,7 +96,8 @@ public class Cas20ProxyReceivingTicketValidationFilter extends AbstractTicketVal
}
logger.trace("Setting proxyReceptorUrl parameter: {}", this.proxyReceptorUrl);
this.millisBetweenCleanUps = Integer.parseInt(getPropertyFromInitParams(filterConfig, "millisBetweenCleanUps", Integer.toString(DEFAULT_MILLIS_BETWEEN_CLEANUPS)));
this.millisBetweenCleanUps = Integer.parseInt(getPropertyFromInitParams(filterConfig, "millisBetweenCleanUps",
Integer.toString(DEFAULT_MILLIS_BETWEEN_CLEANUPS)));
super.initInternal(filterConfig);
}
@ -114,7 +115,8 @@ public class Cas20ProxyReceivingTicketValidationFilter extends AbstractTicketVal
this.timer.schedule(this.timerTask, this.millisBetweenCleanUps, this.millisBetweenCleanUps);
}
private <T> T createNewTicketValidator(final String ticketValidatorClass, final String casServerUrlPrefix, final Class<T> clazz) {
private <T> T createNewTicketValidator(final String ticketValidatorClass, final String casServerUrlPrefix,
final Class<T> clazz) {
if (CommonUtils.isBlank(ticketValidatorClass)) {
return ReflectUtils.newInstance(clazz, casServerUrlPrefix);
}
@ -136,24 +138,28 @@ public class Cas20ProxyReceivingTicketValidationFilter extends AbstractTicketVal
final Cas20ServiceTicketValidator validator;
if (CommonUtils.isNotBlank(allowAnyProxy) || CommonUtils.isNotBlank(allowedProxyChains)) {
final Cas20ProxyTicketValidator v = createNewTicketValidator(ticketValidatorClass, casServerUrlPrefix, Cas20ProxyTicketValidator.class);
final Cas20ProxyTicketValidator v = createNewTicketValidator(ticketValidatorClass, casServerUrlPrefix,
Cas20ProxyTicketValidator.class);
v.setAcceptAnyProxy(parseBoolean(allowAnyProxy));
v.setAllowedProxyChains(CommonUtils.createProxyList(allowedProxyChains));
validator = v;
} else {
validator = createNewTicketValidator(ticketValidatorClass, casServerUrlPrefix, Cas20ServiceTicketValidator.class);
validator = createNewTicketValidator(ticketValidatorClass, casServerUrlPrefix,
Cas20ServiceTicketValidator.class);
}
validator.setProxyCallbackUrl(getPropertyFromInitParams(filterConfig, "proxyCallbackUrl", null));
validator.setProxyGrantingTicketStorage(this.proxyGrantingTicketStorage);
final HttpURLConnectionFactory factory = new HttpsURLConnectionFactory(getHostnameVerifier(filterConfig), getSSLConfig(filterConfig));
final HttpURLConnectionFactory factory = new HttpsURLConnectionFactory(getHostnameVerifier(filterConfig),
getSSLConfig(filterConfig));
validator.setURLConnectionFactory(factory);
validator.setProxyRetriever(new Cas20ProxyRetriever(casServerUrlPrefix, getPropertyFromInitParams(filterConfig, "encoding", null), factory));
validator.setProxyRetriever(new Cas20ProxyRetriever(casServerUrlPrefix, getPropertyFromInitParams(filterConfig,
"encoding", null), factory));
validator.setRenew(parseBoolean(getPropertyFromInitParams(filterConfig, "renew", "false")));
validator.setEncoding(getPropertyFromInitParams(filterConfig, "encoding", null));
final Map<String,String> additionalParameters = new HashMap<String,String>();
final Map<String, String> additionalParameters = new HashMap<String, String>();
final List<String> params = Arrays.asList(RESERVED_INIT_PARAMS);
for (final Enumeration<?> e = filterConfig.getInitParameterNames(); e.hasMoreElements();) {
@ -176,7 +182,8 @@ public class Cas20ProxyReceivingTicketValidationFilter extends AbstractTicketVal
/**
* This processes the ProxyReceptor request before the ticket validation code executes.
*/
protected final boolean preFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
protected final boolean preFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
final FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpServletResponse response = (HttpServletResponse) servletResponse;
final String requestUri = request.getRequestURI();

View File

@ -18,9 +18,8 @@
*/
package org.jasig.cas.client.validation;
import org.jasig.cas.client.util.XmlUtils;
import java.util.List;
import org.jasig.cas.client.util.XmlUtils;
/**
* Extension to the traditional Service Ticket validation that will validate service tickets and proxy tickets.
@ -37,7 +36,7 @@ public class Cas20ProxyTicketValidator extends Cas20ServiceTicketValidator {
/** Allows for an empty chain of proxy callback urls. **/
private boolean allowEmptyProxyChain = true;
public Cas20ProxyTicketValidator(final String casServerUrlPrefix) {
super(casServerUrlPrefix);
}
@ -50,9 +49,10 @@ public class Cas20ProxyTicketValidator extends Cas20ServiceTicketValidator {
return "proxyValidate";
}
protected void customParseResponse(final String response, final Assertion assertion) throws TicketValidationException {
protected void customParseResponse(final String response, final Assertion assertion)
throws TicketValidationException {
final List<String> proxies = XmlUtils.getTextForElements(response, "proxy");
// this means there was nothing in the proxy chain, which is okay
if ((this.allowEmptyProxyChain && proxies.isEmpty()) || this.acceptAnyProxy) {
return;
@ -79,7 +79,7 @@ public class Cas20ProxyTicketValidator extends Cas20ServiceTicketValidator {
}
protected final boolean isAllowEmptyProxyChain() {
return this.allowEmptyProxyChain;
return this.allowEmptyProxyChain;
}
/**
@ -88,6 +88,6 @@ public class Cas20ProxyTicketValidator extends Cas20ServiceTicketValidator {
* @param allowEmptyProxyChain whether to allow empty proxy chains or not. True if so, false otherwise.
*/
public final void setAllowEmptyProxyChain(final boolean allowEmptyProxyChain) {
this.allowEmptyProxyChain = allowEmptyProxyChain;
this.allowEmptyProxyChain = allowEmptyProxyChain;
}
}

View File

@ -18,6 +18,10 @@
*/
package org.jasig.cas.client.validation;
import java.io.StringReader;
import java.util.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.jasig.cas.client.proxy.Cas20ProxyRetriever;
@ -31,11 +35,6 @@ import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.StringReader;
import java.util.*;
/**
* Implementation of the TicketValidator that will validate Service Tickets in compliance with the CAS 2.
*
@ -70,7 +69,7 @@ public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTick
*
* @param urlParameters the Map containing the existing parameters to send to the server.
*/
protected final void populateUrlAttributeMap(final Map<String,String> urlParameters) {
protected final void populateUrlAttributeMap(final Map<String, String> urlParameters) {
urlParameters.put("pgtUrl", encodeUrl(this.proxyCallbackUrl));
}
@ -87,12 +86,12 @@ public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTick
final String principal = XmlUtils.getTextForElement(response, "user");
final String proxyGrantingTicketIou = XmlUtils.getTextForElement(response, "proxyGrantingTicket");
final String proxyGrantingTicket;
if (CommonUtils.isBlank(proxyGrantingTicketIou) || this.proxyGrantingTicketStorage == null) {
proxyGrantingTicket = null;
proxyGrantingTicket = null;
} else {
proxyGrantingTicket = this.proxyGrantingTicketStorage.retrieve(proxyGrantingTicketIou);
proxyGrantingTicket = this.proxyGrantingTicketStorage.retrieve(proxyGrantingTicketIou);
}
if (CommonUtils.isEmpty(principal)) {
@ -100,9 +99,10 @@ public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTick
}
final Assertion assertion;
final Map<String,Object> attributes = extractCustomAttributes(response);
final Map<String, Object> attributes = extractCustomAttributes(response);
if (CommonUtils.isNotBlank(proxyGrantingTicket)) {
final AttributePrincipal attributePrincipal = new AttributePrincipalImpl(principal, attributes, proxyGrantingTicket, this.proxyRetriever);
final AttributePrincipal attributePrincipal = new AttributePrincipalImpl(principal, attributes,
proxyGrantingTicket, this.proxyRetriever);
assertion = new AssertionImpl(attributePrincipal);
} else {
assertion = new AssertionImpl(new AttributePrincipalImpl(principal, attributes));
@ -131,7 +131,7 @@ public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTick
* @param xml the XML to parse.
* @return the map of attributes.
*/
protected Map<String,Object> extractCustomAttributes(final String xml) {
protected Map<String, Object> extractCustomAttributes(final String xml) {
final SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(false);
@ -155,7 +155,8 @@ public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTick
* @param assertion the partially constructed assertion.
* @throws TicketValidationException if there is a problem constructing the Assertion.
*/
protected void customParseResponse(final String response, final Assertion assertion) throws TicketValidationException {
protected void customParseResponse(final String response, final Assertion assertion)
throws TicketValidationException {
// nothing to do
}
@ -199,7 +200,8 @@ public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTick
}
@Override
public void startElement(final String namespaceURI, final String localName, final String qName, final Attributes attributes) throws SAXException {
public void startElement(final String namespaceURI, final String localName, final String qName,
final Attributes attributes) throws SAXException {
if ("attributes".equals(localName)) {
this.foundAttributes = true;
} else if (this.foundAttributes) {
@ -216,7 +218,8 @@ public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTick
}
@Override
public void endElement(final String namespaceURI, final String localName, final String qName) throws SAXException {
public void endElement(final String namespaceURI, final String localName, final String qName)
throws SAXException {
if ("attributes".equals(localName)) {
this.foundAttributes = false;
this.currentAttribute = null;

View File

@ -28,11 +28,11 @@ package org.jasig.cas.client.validation;
public final class InvalidProxyChainTicketValidationException extends TicketValidationException {
/**
* Unique Id for Serialization
*/
private static final long serialVersionUID = -7736653266370691534L;
* Unique Id for Serialization
*/
private static final long serialVersionUID = -7736653266370691534L;
/**
/**
* Constructs an exception with the supplied message.
* @param string the supplied message.
*/

View File

@ -18,11 +18,10 @@
*/
package org.jasig.cas.client.validation;
import org.jasig.cas.client.util.CommonUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.List;
import org.jasig.cas.client.util.CommonUtils;
/**
* Holding class for the proxy list to make Spring configuration easier.
@ -53,8 +52,8 @@ public final class ProxyList {
return false;
}
public String toString() {
return this.proxyChains.toString();
return this.proxyChains.toString();
}
}

View File

@ -18,14 +18,13 @@
*/
package org.jasig.cas.client.validation;
import org.jasig.cas.client.util.CommonUtils;
import java.beans.PropertyEditorSupport;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.jasig.cas.client.util.CommonUtils;
/**
* Convert a String-formatted list of acceptable proxies to an array.
@ -37,27 +36,27 @@ import java.util.List;
*/
public final class ProxyListEditor extends PropertyEditorSupport {
public void setAsText(final String text) throws IllegalArgumentException {
final BufferedReader reader = new BufferedReader(new StringReader(text));
final List<String[]> proxyChains = new ArrayList<String[]>();
public void setAsText(final String text) throws IllegalArgumentException {
final BufferedReader reader = new BufferedReader(new StringReader(text));
final List<String[]> proxyChains = new ArrayList<String[]>();
try {
String line;
while ((line = reader.readLine()) != null) {
if (CommonUtils.isNotBlank(line)) {
proxyChains.add(line.trim().split(" "));
}
}
} catch (final IOException e) {
// ignore this
} finally {
try {
reader.close();
} catch (final IOException e) {
// nothing to do
}
}
try {
String line;
while ((line = reader.readLine()) != null) {
if (CommonUtils.isNotBlank(line)) {
proxyChains.add(line.trim().split(" "));
}
}
} catch (final IOException e) {
// ignore this
} finally {
try {
reader.close();
} catch (final IOException e) {
// nothing to do
}
}
setValue(new ProxyList(proxyChains));
}
setValue(new ProxyList(proxyChains));
}
}

View File

@ -20,9 +20,8 @@ package org.jasig.cas.client.validation;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import org.jasig.cas.client.ssl.HttpsURLConnectionFactory;
import org.jasig.cas.client.ssl.HttpURLConnectionFactory;
import org.jasig.cas.client.ssl.HttpsURLConnectionFactory;
/**
* Implementation of TicketValidationFilter that can instanciate a SAML 1.1 Ticket Validator.
@ -52,16 +51,19 @@ public class Saml11TicketValidationFilter extends AbstractTicketValidationFilter
}
protected final TicketValidator getTicketValidator(final FilterConfig filterConfig) {
final Saml11TicketValidator validator = new Saml11TicketValidator(getPropertyFromInitParams(filterConfig, "casServerUrlPrefix", null));
final Saml11TicketValidator validator = new Saml11TicketValidator(getPropertyFromInitParams(filterConfig,
"casServerUrlPrefix", null));
final String tolerance = getPropertyFromInitParams(filterConfig, "tolerance", "1000");
validator.setTolerance(Long.parseLong(tolerance));
validator.setRenew(parseBoolean(getPropertyFromInitParams(filterConfig, "renew", "false")));
final HttpURLConnectionFactory factory = new HttpsURLConnectionFactory(getHostnameVerifier(filterConfig), getSSLConfig(filterConfig));
final HttpURLConnectionFactory factory = new HttpsURLConnectionFactory(getHostnameVerifier(filterConfig),
getSSLConfig(filterConfig));
validator.setURLConnectionFactory(factory);
validator.setEncoding(getPropertyFromInitParams(filterConfig, "encoding", null));
validator.setDisableXmlSchemaValidation(parseBoolean(getPropertyFromInitParams(filterConfig, "disableXmlSchemaValidation", "false")));
validator.setDisableXmlSchemaValidation(parseBoolean(getPropertyFromInitParams(filterConfig,
"disableXmlSchemaValidation", "false")));
return validator;
}
}

View File

@ -18,13 +18,19 @@
*/
package org.jasig.cas.client.validation;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.jasig.cas.client.util.CommonUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Interval;
import org.opensaml.*;
import org.opensaml.Configuration;
import org.opensaml.DefaultBootstrap;
import org.opensaml.common.IdentifierGenerator;
import org.opensaml.common.impl.SecureRandomIdentifierGenerator;
import org.opensaml.saml1.core.*;
@ -40,12 +46,6 @@ import org.opensaml.xml.schema.XSString;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;
/**
* TicketValidator that can understand validating a SAML artifact. This includes the SOAP request/response.
*
@ -69,6 +69,7 @@ public final class Saml11TicketValidator extends AbstractUrlBasedTicketValidator
private final BasicParserPool basicParserPool;
private final IdentifierGenerator identifierGenerator;
public Saml11TicketValidator(final String casServerUrlPrefix) {
super(casServerUrlPrefix);
this.basicParserPool = new BasicParserPool();
@ -140,30 +141,34 @@ public final class Saml11TicketValidator extends AbstractUrlBasedTicketValidator
}
final List<Attribute> attributes = getAttributesFor(assertion, subject);
final Map<String,Object> personAttributes = new HashMap<String,Object>();
final Map<String, Object> personAttributes = new HashMap<String, Object>();
for (final Attribute samlAttribute : attributes) {
final List<?> values = getValuesFrom(samlAttribute);
personAttributes.put(samlAttribute.getAttributeName(), values.size() == 1 ? values.get(0) : values);
}
final AttributePrincipal principal = new AttributePrincipalImpl(subject.getNameIdentifier().getNameIdentifier(), personAttributes);
final AttributePrincipal principal = new AttributePrincipalImpl(subject.getNameIdentifier()
.getNameIdentifier(), personAttributes);
final Map<String,Object> authenticationAttributes = new HashMap<String,Object>();
authenticationAttributes.put("samlAuthenticationStatement::authMethod", authenticationStatement.getAuthenticationMethod());
final Map<String, Object> authenticationAttributes = new HashMap<String, Object>();
authenticationAttributes.put("samlAuthenticationStatement::authMethod",
authenticationStatement.getAuthenticationMethod());
final DateTime notBefore = assertion.getConditions().getNotBefore();
final DateTime notOnOrAfter = assertion.getConditions().getNotOnOrAfter();
final DateTime authenticationInstant = authenticationStatement.getAuthenticationInstant();
return new AssertionImpl(principal, notBefore.toDate(), notOnOrAfter.toDate(), authenticationInstant.toDate(), authenticationAttributes);
return new AssertionImpl(principal, notBefore.toDate(), notOnOrAfter.toDate(),
authenticationInstant.toDate(), authenticationAttributes);
}
} catch (final UnmarshallingException e) {
} catch (final UnmarshallingException e) {
throw new TicketValidationException(e);
} catch (final XMLParserException e) {
throw new TicketValidationException(e);
}
throw new TicketValidationException("No Assertion found within valid time range. Either there's a replay of the ticket or there's clock drift. Check tolerance range, or server/client synchronization.");
throw new TicketValidationException(
"No Assertion found within valid time range. Either there's a replay of the ticket or there's clock drift. Check tolerance range, or server/client synchronization.");
}
private boolean isValidAssertion(final org.opensaml.saml1.core.Assertion assertion) {
@ -205,7 +210,8 @@ public final class Saml11TicketValidator extends AbstractUrlBasedTicketValidator
private List<Attribute> getAttributesFor(final org.opensaml.saml1.core.Assertion assertion, final Subject subject) {
final List<Attribute> attributes = new ArrayList<Attribute>();
for (final AttributeStatement attribute : assertion.getAttributeStatements()) {
if (subject.getNameIdentifier().getNameIdentifier().equals(attribute.getSubject().getNameIdentifier().getNameIdentifier())) {
if (subject.getNameIdentifier().getNameIdentifier()
.equals(attribute.getSubject().getNameIdentifier().getNameIdentifier())) {
attributes.addAll(attribute.getAttributes());
}
}
@ -228,17 +234,22 @@ public final class Saml11TicketValidator extends AbstractUrlBasedTicketValidator
}
protected String retrieveResponseFromServer(final URL validationUrl, final String ticket) {
final String MESSAGE_TO_SEND = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><samlp:Request xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" MajorVersion=\"1\" MinorVersion=\"1\" RequestID=\"" + this.identifierGenerator.generateIdentifier() + "\" IssueInstant=\"" + CommonUtils.formatForUtcTime(new Date()) + "\">"
+ "<samlp:AssertionArtifact>" + ticket
final String MESSAGE_TO_SEND = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><samlp:Request xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" MajorVersion=\"1\" MinorVersion=\"1\" RequestID=\""
+ this.identifierGenerator.generateIdentifier()
+ "\" IssueInstant=\""
+ CommonUtils.formatForUtcTime(new Date())
+ "\">"
+ "<samlp:AssertionArtifact>"
+ ticket
+ "</samlp:AssertionArtifact></samlp:Request></SOAP-ENV:Body></SOAP-ENV:Envelope>";
HttpURLConnection conn = null;
DataOutputStream out = null;
BufferedReader in = null;
try {
conn = this.getURLConnectionFactory().buildHttpURLConnection(validationUrl.openConnection());
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml");
conn.setRequestProperty("Content-Type", "text/xml");
conn.setRequestProperty("Content-Length", Integer.toString(MESSAGE_TO_SEND.length()));
conn.setRequestProperty("SOAPAction", "http://www.oasis-open.org/committees/security");
conn.setUseCaches(false);
@ -248,8 +259,10 @@ public final class Saml11TicketValidator extends AbstractUrlBasedTicketValidator
out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(MESSAGE_TO_SEND);
out.flush();
in = new BufferedReader(CommonUtils.isNotBlank(getEncoding()) ? new InputStreamReader(conn.getInputStream(), Charset.forName(getEncoding())) : new InputStreamReader(conn.getInputStream()));
in = new BufferedReader(CommonUtils.isNotBlank(getEncoding()) ? new InputStreamReader(
conn.getInputStream(), Charset.forName(getEncoding())) : new InputStreamReader(
conn.getInputStream()));
final StringBuilder buffer = new StringBuilder(256);
String line;
@ -259,7 +272,7 @@ public final class Saml11TicketValidator extends AbstractUrlBasedTicketValidator
}
return buffer.toString();
} catch (final IOException e) {
throw new RuntimeException(e);
throw new RuntimeException(e);
} finally {
CommonUtils.closeQuietly(out);
CommonUtils.closeQuietly(in);

View File

@ -28,11 +28,11 @@ package org.jasig.cas.client.validation;
public class TicketValidationException extends Exception {
/**
* Unique Id for Serialization
*/
private static final long serialVersionUID = -7036248720402711806L;
* Unique Id for Serialization
*/
private static final long serialVersionUID = -7036248720402711806L;
/**
/**
* Constructs an exception with the supplied message.
*
* @param string the message

View File

@ -45,11 +45,13 @@ public final class PublicTestHttpServer extends Thread {
private static Map<Integer, PublicTestHttpServer> serverMap = new HashMap<Integer, PublicTestHttpServer>();
private PublicTestHttpServer(String data, String encoding, String MIMEType, int port) throws UnsupportedEncodingException {
private PublicTestHttpServer(String data, String encoding, String MIMEType, int port)
throws UnsupportedEncodingException {
this(data.getBytes(encoding), encoding, MIMEType, port);
}
private PublicTestHttpServer(byte[] data, String encoding, String MIMEType, int port) throws UnsupportedEncodingException {
private PublicTestHttpServer(byte[] data, String encoding, String MIMEType, int port)
throws UnsupportedEncodingException {
this.content = data;
this.port = port;
this.encoding = encoding;

View File

@ -23,10 +23,8 @@ import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collections;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.jasig.cas.client.authentication.SimpleGroup;
import org.jasig.cas.client.authentication.SimplePrincipal;
@ -43,7 +41,7 @@ import org.jasig.cas.client.validation.AssertionImpl;
*
*/
public class SerializationTests extends TestCase {
public void testSerializeDeserialize() throws Exception {
final Object[] subjects = getTestSubjects();
for (int i = 0; i < subjects.length; i++) {
@ -56,7 +54,7 @@ public class SerializationTests extends TestCase {
} finally {
out.close();
}
final ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
final ObjectInputStream in = new ObjectInputStream(byteIn);
try {
@ -72,17 +70,11 @@ public class SerializationTests extends TestCase {
private Object[] getTestSubjects() {
final SimplePrincipal simplePrincipal = new SimplePrincipal("simple");
final SimpleGroup simpleGroup = new SimpleGroup("group");
final AttributePrincipalImpl attributePrincipal =
new AttributePrincipalImpl("attr", Collections.<String,Object>singletonMap("LOA", "3"));
final AssertionPrincipal assertionPrincipal = new AssertionPrincipal(
"assertion",
new AssertionImpl(attributePrincipal, Collections.<String,Object>singletonMap("authenticationMethod", "username")));
return new Object[] {
simplePrincipal,
simpleGroup,
attributePrincipal,
assertionPrincipal,
};
final AttributePrincipalImpl attributePrincipal = new AttributePrincipalImpl("attr",
Collections.<String, Object> singletonMap("LOA", "3"));
final AssertionPrincipal assertionPrincipal = new AssertionPrincipal("assertion", new AssertionImpl(
attributePrincipal, Collections.<String, Object> singletonMap("authenticationMethod", "username")));
return new Object[] { simplePrincipal, simpleGroup, attributePrincipal, assertionPrincipal, };
}
}

View File

@ -1,7 +1,6 @@
package org.jasig.cas.client.authentication;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;

View File

@ -1,12 +1,11 @@
package org.jasig.cas.client.authentication;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.junit.Assert.*;
public class FacesCompatibleAuthenticationRedirectStrategyTests {
private FacesCompatibleAuthenticationRedirectStrategy strategy;

View File

@ -18,25 +18,19 @@
*/
package org.jasig.cas.client.jaas;
import static org.junit.Assert.*;
import java.security.Principal;
import java.security.acl.Group;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginException;
import org.jasig.cas.client.PublicTestHttpServer;
import org.jasig.cas.client.validation.TicketValidationException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit test for {@link CasLoginModule} class.
*
@ -49,23 +43,23 @@ public class CasLoginModuleTests {
private static final PublicTestHttpServer server = PublicTestHttpServer.instance(8091);
private static final String CONST_CAS_SERVER_URL = "http://localhost:8091/";
private CasLoginModule module;
private Subject subject;
private Map<String,String> options;
/* @AfterClass
public static void classCleanUp() {
server.shutdown();
}*/
private CasLoginModule module;
private Subject subject;
private Map<String, String> options;
/* @AfterClass
public static void classCleanUp() {
server.shutdown();
}*/
@Before
public void setUp() throws Exception {
module = new CasLoginModule();
subject = new Subject();
options = new HashMap<String,String>();
options = new HashMap<String, String>();
options.put("service", "https://service.example.com/webapp");
options.put("ticketValidatorClass", "org.jasig.cas.client.validation.Cas20ServiceTicketValidator");
options.put("casServerUrlPrefix", CONST_CAS_SERVER_URL);
@ -86,15 +80,11 @@ public class CasLoginModuleTests {
final String SERVICE = "https://example.com/service";
final String TICKET = "ST-100000-aA5Yuvrxzpv8Tau1cYQ7-srv1";
final String RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>"
+ "<cas:authenticationSuccess><cas:user>"
+ USERNAME
+ "<cas:authenticationSuccess><cas:user>" + USERNAME
+ "</cas:user></cas:authenticationSuccess></cas:serviceResponse>";
server.content = RESPONSE.getBytes(server.encoding);
module.initialize(
subject,
new ServiceAndTicketCallbackHandler(SERVICE, TICKET),
new HashMap<String,Object>(),
module.initialize(subject, new ServiceAndTicketCallbackHandler(SERVICE, TICKET), new HashMap<String, Object>(),
options);
module.login();
module.commit();
@ -115,10 +105,7 @@ public class CasLoginModuleTests {
final String TICKET = "ST-200000-aA5Yuvrxzpv8Tau1cYQ7-srv1";
final String RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'><cas:authenticationFailure code=\"INVALID_TICKET\">Ticket ST-200000-aA5Yuvrxzpv8Tau1cYQ7-srv1 not recognized</cas:authenticationFailure></cas:serviceResponse>";
server.content = RESPONSE.getBytes(server.encoding);
module.initialize(
subject,
new ServiceAndTicketCallbackHandler(SERVICE, TICKET),
new HashMap<String,Object>(),
module.initialize(subject, new ServiceAndTicketCallbackHandler(SERVICE, TICKET), new HashMap<String, Object>(),
options);
try {
module.login();
@ -153,8 +140,7 @@ public class CasLoginModuleTests {
final String SERVICE = "https://example.com/service";
final String TICKET = "ST-300000-aA5Yuvrxzpv8Tau1cYQ7-srv1";
final String SUCCESS_RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>"
+ "<cas:authenticationSuccess><cas:user>"
+ USERNAME
+ "<cas:authenticationSuccess><cas:user>" + USERNAME
+ "</cas:user></cas:authenticationSuccess></cas:serviceResponse>";
final String FAILURE_RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'><cas:authenticationFailure code=\"INVALID_TICKET\">Ticket ST-300000-aA5Yuvrxzpv8Tau1cYQ7-srv1 not recognized</cas:authenticationFailure></cas:serviceResponse>";
@ -162,31 +148,26 @@ public class CasLoginModuleTests {
options.put("cacheTimeout", "1");
server.content = SUCCESS_RESPONSE.getBytes(server.encoding);
module.initialize(
subject,
new ServiceAndTicketCallbackHandler(SERVICE, TICKET),
new HashMap<String,Object>(),
module.initialize(subject, new ServiceAndTicketCallbackHandler(SERVICE, TICKET), new HashMap<String, Object>(),
options);
module.login();
module.commit();
assertEquals(this.subject.getPrincipals().size(), 3);
assertEquals(TICKET, this.subject.getPrivateCredentials().iterator().next().toString());
Thread.sleep(2000);
module.logout();
assertEquals(0, subject.getPrincipals().size());
assertEquals(0, subject.getPrivateCredentials().size());
server.content = FAILURE_RESPONSE.getBytes(server.encoding);
module.initialize(
subject,
new ServiceAndTicketCallbackHandler(SERVICE, TICKET),
new HashMap<String,Object>(),
module.initialize(subject, new ServiceAndTicketCallbackHandler(SERVICE, TICKET), new HashMap<String, Object>(),
options);
module.login();
module.commit();
assertEquals(this.subject.getPrincipals().size(), 3);
assertEquals(TICKET, this.subject.getPrivateCredentials().iterator().next().toString());
}
/**
* Verify that cached assertions that are expired are never be accessible
* by {@link org.jasig.cas.client.jaas.CasLoginModule#login()} method.
@ -199,8 +180,7 @@ public class CasLoginModuleTests {
final String SERVICE = "https://example.com/service";
final String TICKET = "ST-12345-ABCDEFGHIJKLMNOPQRSTUVWXYZ-hosta";
final String SUCCESS_RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>"
+ "<cas:authenticationSuccess><cas:user>"
+ USERNAME
+ "<cas:authenticationSuccess><cas:user>" + USERNAME
+ "</cas:user></cas:authenticationSuccess></cas:serviceResponse>";
final String FAILURE_RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'><cas:authenticationFailure code=\"INVALID_TICKET\">Ticket ST-12345-ABCDEFGHIJKLMNOPQRSTUVWXYZ-hosta not recognized</cas:authenticationFailure></cas:serviceResponse>";
@ -210,10 +190,7 @@ public class CasLoginModuleTests {
options.put("cacheTimeout", "1");
server.content = SUCCESS_RESPONSE.getBytes(server.encoding);
module.initialize(
subject,
new ServiceAndTicketCallbackHandler(SERVICE, TICKET),
new HashMap<String, Object>(),
module.initialize(subject, new ServiceAndTicketCallbackHandler(SERVICE, TICKET), new HashMap<String, Object>(),
options);
assertTrue(module.login());
module.commit();
@ -221,10 +198,7 @@ public class CasLoginModuleTests {
Thread.sleep(1100);
// Assertion should now be expired from cache
server.content = FAILURE_RESPONSE.getBytes(server.encoding);
module.initialize(
subject,
new ServiceAndTicketCallbackHandler(SERVICE, TICKET),
new HashMap<String, Object>(),
module.initialize(subject, new ServiceAndTicketCallbackHandler(SERVICE, TICKET), new HashMap<String, Object>(),
options);
try {
module.login();
@ -233,8 +207,9 @@ public class CasLoginModuleTests {
assertTrue(e.getCause() instanceof TicketValidationException);
}
}
private boolean hasPrincipalName(final Subject subject, final Class<? extends Principal> principalClass, final String name) {
private boolean hasPrincipalName(final Subject subject, final Class<? extends Principal> principalClass,
final String name) {
final Set<? extends Principal> principals = subject.getPrincipals(principalClass);
for (Principal p : principals) {
if (p.getName().equals(name)) {

View File

@ -19,10 +19,8 @@
package org.jasig.cas.client.proxy;
import java.util.TimerTask;
import org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter;
import junit.framework.TestCase;
import org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter;
/**
* Unit test for the {@link CleanUpTimerTask}
@ -40,7 +38,7 @@ public class CleanUpTimerTaskTest extends TestCase {
timerTask.run();
assertTrue(storage.cleanUpWasCalled());
}
/**
* implementation of the storage interface used only for testing
*
@ -48,11 +46,11 @@ public class CleanUpTimerTaskTest extends TestCase {
*/
private static final class ProxyGrantingTicketStorageTestImpl implements ProxyGrantingTicketStorage {
private boolean cleanUpCalled = false;
public boolean cleanUpWasCalled() {
return cleanUpCalled;
}
public void cleanUp() {
cleanUpCalled = true;
}

View File

@ -18,7 +18,6 @@
*/
package org.jasig.cas.client.proxy;
import junit.framework.TestCase;
import org.junit.Assert;
import org.junit.Test;
@ -36,15 +35,15 @@ public class ProxyGrantingTicketStorageImplTest {
@Test
public void cleanUp() throws Exception {
String proxyGrantingTicketIou = "proxyGrantingTicketIou";
int timeout = 250;
this.storage.save(proxyGrantingTicketIou, "proxyGrantingTicket");
// sleep long enough for the ticket to timeout
Thread.sleep(timeout * 2);
this.storage.cleanUp();
Assert.assertNull(this.storage.retrieve(proxyGrantingTicketIou));
}

View File

@ -18,12 +18,12 @@
*/
package org.jasig.cas.client.session;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.junit.Assert.*;
/**
* @author Matt Brown <matt.brown@citrix.com>
* @version $Revision$ $Date$

View File

@ -46,8 +46,7 @@ public class WhitelistHostnameVerifierTests extends TestCase {
* Test method for {@link WhitelistHostnameVerifier#verify(String, SSLSession)}.
*/
public void testVerify() {
final WhitelistHostnameVerifier verifier = new WhitelistHostnameVerifier(
"red.vt.edu, green.vt.edu,blue.vt.edu");
final WhitelistHostnameVerifier verifier = new WhitelistHostnameVerifier("red.vt.edu, green.vt.edu,blue.vt.edu");
Assert.assertTrue(verifier.verify("red.vt.edu", null));
Assert.assertTrue(verifier.verify("green.vt.edu", null));
Assert.assertTrue(verifier.verify("blue.vt.edu", null));

View File

@ -18,17 +18,15 @@
*/
package org.jasig.cas.client.util;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
* @author Scott Battaglia
@ -57,7 +55,8 @@ public final class CasFilterTests {
}
private static class TestCasFilter extends AbstractCasFilter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
// nothing to do
}
}

View File

@ -18,13 +18,12 @@
*/
package org.jasig.cas.client.util;
import java.util.ArrayList;
import java.util.Collection;
import junit.framework.TestCase;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
/**
* Tests for the CommonUtils.
*
@ -43,7 +42,7 @@ public final class CommonUtilsTests extends TestCase {
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '?') {
count ++;
count++;
}
}
@ -126,7 +125,8 @@ public final class CommonUtilsTests extends TestCase {
request.setScheme("https");
request.setSecure(true);
final MockHttpServletResponse response = new MockHttpServletResponse();
final String constructedUrl = CommonUtils.constructServiceUrl(request, response, null, "www.myserver.com", "ticket", false);
final String constructedUrl = CommonUtils.constructServiceUrl(request, response, null, "www.myserver.com",
"ticket", false);
assertEquals(CONST_MY_URL, constructedUrl);
}
@ -138,7 +138,8 @@ public final class CommonUtilsTests extends TestCase {
request.setScheme("https");
request.setSecure(true);
final MockHttpServletResponse response = new MockHttpServletResponse();
final String constructedUrl = CommonUtils.constructServiceUrl(request, response, null, "www.amazon.com www.bestbuy.com www.myserver.com", "ticket", false);
final String constructedUrl = CommonUtils.constructServiceUrl(request, response, null,
"www.amazon.com www.bestbuy.com www.myserver.com", "ticket", false);
assertEquals(CONST_MY_URL, constructedUrl);
}
@ -149,7 +150,8 @@ public final class CommonUtilsTests extends TestCase {
request.setScheme("https");
request.setSecure(true);
final MockHttpServletResponse response = new MockHttpServletResponse();
final String constructedUrl = CommonUtils.constructServiceUrl(request, response, null, "http://www.amazon.com https://www.bestbuy.com https://www.myserver.com", "ticket", false);
final String constructedUrl = CommonUtils.constructServiceUrl(request, response, null,
"http://www.amazon.com https://www.bestbuy.com https://www.myserver.com", "ticket", false);
assertEquals(CONST_MY_URL, constructedUrl);
}
}

View File

@ -18,8 +18,16 @@
*/
package org.jasig.cas.client.util;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import junit.framework.TestCase;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.jasig.cas.client.validation.AssertionImpl;
@ -28,16 +36,6 @@ import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Tests for the HttpServletRequestWrapperFilter.
*
@ -56,17 +54,15 @@ public final class HttpServletRequestWrapperFilterTests extends TestCase {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpSession session = new MockHttpSession();
session.setAttribute(
AbstractCasFilter.CONST_CAS_ASSERTION,
new AssertionImpl("test"));
session.setAttribute(AbstractCasFilter.CONST_CAS_ASSERTION, new AssertionImpl("test"));
request.setSession(session);
filter.doFilter(request, new MockHttpServletResponse(), createFilterChain());
assertEquals("test", this.mockRequest.getRemoteUser());
filter.destroy();
}
public void testIsUserInRole() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpSession session = new MockHttpSession();
@ -75,13 +71,11 @@ public final class HttpServletRequestWrapperFilterTests extends TestCase {
config.addInitParameter("roleAttribute", "memberOf");
final HttpServletRequestWrapperFilter filter = new HttpServletRequestWrapperFilter();
filter.init(config);
final Map<String,Object> attributes = new HashMap<String,Object>();
final Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("memberOf", "administrators");
final AttributePrincipal principal = new AttributePrincipalImpl("alice", attributes);
session.setAttribute(
AbstractCasFilter.CONST_CAS_ASSERTION,
new AssertionImpl(principal));
session.setAttribute(AbstractCasFilter.CONST_CAS_ASSERTION, new AssertionImpl(principal));
request.setSession(session);
@ -94,7 +88,7 @@ public final class HttpServletRequestWrapperFilterTests extends TestCase {
filter.destroy();
}
public void testIsUserInRoleCaseInsensitive() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpSession session = new MockHttpSession();
@ -104,13 +98,11 @@ public final class HttpServletRequestWrapperFilterTests extends TestCase {
config.addInitParameter("ignoreCase", "true");
final HttpServletRequestWrapperFilter filter = new HttpServletRequestWrapperFilter();
filter.init(config);
final Map<String,Object> attributes = new HashMap<String,Object>();
attributes.put("groupMembership", Arrays.asList(new Object[] {"animals", "ducks"}));
final Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("groupMembership", Arrays.asList(new Object[] { "animals", "ducks" }));
final AttributePrincipal principal = new AttributePrincipalImpl("daffy", attributes);
session.setAttribute(
AbstractCasFilter.CONST_CAS_ASSERTION,
new AssertionImpl(principal));
session.setAttribute(AbstractCasFilter.CONST_CAS_ASSERTION, new AssertionImpl(principal));
request.setSession(session);
@ -128,8 +120,7 @@ public final class HttpServletRequestWrapperFilterTests extends TestCase {
private FilterChain createFilterChain() {
return new FilterChain() {
public void doFilter(ServletRequest request,
ServletResponse response) throws IOException, ServletException {
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
HttpServletRequestWrapperFilterTests.this.mockRequest = (HttpServletRequest) request;
}

View File

@ -33,7 +33,7 @@ public class MethodFlag {
public boolean wasCalled() {
return called;
}
public void setCalled() {
called = true;
}

View File

@ -33,9 +33,8 @@ public class ReflectUtilsTests extends TestCase {
* Test method for {@link org.jasig.cas.client.util.ReflectUtils#newInstance(java.lang.String, java.lang.Object[])}.
*/
public void testNewInstanceStringObjectArray() {
final Object result = ReflectUtils.newInstance(
"org.jasig.cas.client.validation.Cas10TicketValidator",
new Object[] {"https://localhost/cas"} );
final Object result = ReflectUtils.newInstance("org.jasig.cas.client.validation.Cas10TicketValidator",
new Object[] { "https://localhost/cas" });
assertNotNull(result);
}
@ -44,13 +43,13 @@ public class ReflectUtilsTests extends TestCase {
*/
public void testSetPropertyStringObjectObject() {
final TestBean bean = new TestBean();
ReflectUtils.setProperty("count", new Integer(30000), bean);
assertEquals(30000, bean.getCount());
ReflectUtils.setProperty("name", "bob", bean);
assertEquals("bob", bean.getName());
ReflectUtils.setProperty("flag", Boolean.TRUE, bean);
assertTrue(bean.isFlag());
}

View File

@ -18,13 +18,12 @@
*/
package org.jasig.cas.client.validation;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import java.util.HashMap;
import java.util.Map;
/**
* Test cases for the {@link AssertionImpl}.
*
@ -36,7 +35,7 @@ public final class AssertionImplTests extends TestCase {
private static final AttributePrincipal CONST_PRINCIPAL = new AttributePrincipalImpl("test");
private static final Map<String,Object> CONST_ATTRIBUTES = new HashMap<String,Object>();
private static final Map<String, Object> CONST_ATTRIBUTES = new HashMap<String, Object>();
static {
CONST_ATTRIBUTES.put("test", "test");
@ -51,8 +50,7 @@ public final class AssertionImplTests extends TestCase {
}
public void testCompleteConstructor() {
final Assertion assertion = new AssertionImpl(CONST_PRINCIPAL,
CONST_ATTRIBUTES);
final Assertion assertion = new AssertionImpl(CONST_PRINCIPAL, CONST_ATTRIBUTES);
assertEquals(CONST_PRINCIPAL, assertion.getPrincipal());
assertEquals(CONST_ATTRIBUTES, assertion.getAttributes());

View File

@ -18,13 +18,12 @@
*/
package org.jasig.cas.client.validation;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockServletContext;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit test for {@link Cas10TicketValidationFilter}.
*

View File

@ -17,15 +17,14 @@
* under the License.
*/
package org.jasig.cas.client.validation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.UnsupportedEncodingException;
import org.jasig.cas.client.PublicTestHttpServer;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import static org.junit.Assert.*;
/**
* Test cases for the {@link Cas10TicketValidator}.
*
@ -57,8 +56,7 @@ public final class Cas10TicketValidatorTests extends AbstractTicketValidatorTest
public void testNoResponse() throws Exception {
server.content = "no\n\n".getBytes(server.encoding);
try {
this.ticketValidator.validate("testTicket",
"myService");
this.ticketValidator.validate("testTicket", "myService");
fail("ValidationException expected.");
} catch (final TicketValidationException e) {
// expected
@ -66,21 +64,17 @@ public final class Cas10TicketValidatorTests extends AbstractTicketValidatorTest
}
@Test
public void testYesResponse() throws TicketValidationException,
UnsupportedEncodingException {
public void testYesResponse() throws TicketValidationException, UnsupportedEncodingException {
server.content = "yes\nusername\n\n".getBytes(server.encoding);
final Assertion assertion = this.ticketValidator.validate("testTicket",
"myService");
final Assertion assertion = this.ticketValidator.validate("testTicket", "myService");
assertEquals(CONST_USERNAME, assertion.getPrincipal().getName());
}
@Test
public void testBadResponse() throws UnsupportedEncodingException {
server.content = "falalala\n\n"
.getBytes(server.encoding);
server.content = "falalala\n\n".getBytes(server.encoding);
try {
this.ticketValidator.validate("testTicket",
"myService");
this.ticketValidator.validate("testTicket", "myService");
fail("ValidationException expected.");
} catch (final TicketValidationException e) {
// expected

View File

@ -20,7 +20,6 @@ package org.jasig.cas.client.validation;
import java.util.Timer;
import java.util.TimerTask;
import junit.framework.TestCase;
import org.jasig.cas.client.proxy.CleanUpTimerTask;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage;
@ -82,7 +81,7 @@ public class Cas20ProxyReceivingTicketValidationFilterTests extends TestCase {
assertTrue(cancelMethodFlag.wasCalled());
}
public void testCallsCleanAllOnSchedule() throws Exception {
public void testCallsCleanAllOnSchedule() throws Exception {
final MethodFlag timerTaskFlag = new MethodFlag();
final Cas20ProxyReceivingTicketValidationFilter filter = newCas20ProxyReceivingTicketValidationFilter();
@ -153,7 +152,8 @@ public void testCallsCleanAllOnSchedule() throws Exception {
filter.setMillisBetweenCleanUps(250);
filter.setTimer(defaultTimer);
filter.setTimerTask(new TimerTask() {
public void run() {}
public void run() {
}
});
filter.init();
@ -165,16 +165,13 @@ public void testCallsCleanAllOnSchedule() throws Exception {
// Test case #2
final MockFilterConfig config2 = new MockFilterConfig();
config2.addInitParameter(
"allowedProxyChains",
"https://a.example.com https://b.example.com");
config2.addInitParameter("allowedProxyChains", "https://a.example.com https://b.example.com");
config2.addInitParameter("casServerUrlPrefix", "https://cas.jasig.org/");
assertNotNull(filter.getTicketValidator(config2));
// Test case #3
final MockFilterConfig config3 = new MockFilterConfig();
config3.addInitParameter(
"allowedProxyChains",
config3.addInitParameter("allowedProxyChains",
"https://a.example.com https://b.example.com\nhttps://c.example.com");
config3.addInitParameter("casServerUrlPrefix", "https://cas.jasig.org/");
assertNotNull(filter.getTicketValidator(config3));
@ -213,4 +210,4 @@ public void testCallsCleanAllOnSchedule() throws Exception {
return filter;
}
}
}

View File

@ -18,6 +18,11 @@
*/
package org.jasig.cas.client.validation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.jasig.cas.client.PublicTestHttpServer;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl;
@ -26,12 +31,6 @@ import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
/**
* Test cases for the {@link Cas20ProxyTicketValidator}.
*
@ -57,7 +56,7 @@ public final class Cas20ProxyTicketValidatorTests extends AbstractTicketValidato
@Before
public void setUp() throws Exception {
final List<String[]> list = new ArrayList<String[]>();
list.add(new String[] {"proxy1", "proxy2", "proxy3"});
list.add(new String[] { "proxy1", "proxy2", "proxy3" });
this.ticketValidator = new Cas20ProxyTicketValidator(CONST_CAS_SERVER_URL_PREFIX + "8089");
this.ticketValidator.setRenew(true);
@ -75,29 +74,26 @@ public final class Cas20ProxyTicketValidatorTests extends AbstractTicketValidato
return new ProxyRetriever() {
/** Unique Id For serialization. */
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public String getProxyTicketIdFor(String proxyGrantingTicketId, String targetService) {
public String getProxyTicketIdFor(String proxyGrantingTicketId, String targetService) {
return "test";
}
};
}
@Test
public void testProxyChainWithValidProxy() throws TicketValidationException,
UnsupportedEncodingException {
public void testProxyChainWithValidProxy() throws TicketValidationException, UnsupportedEncodingException {
final String USERNAME = "username";
final String RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'><cas:authenticationSuccess><cas:user>username</cas:user><cas:proxyGrantingTicket>PGTIOU-84678-8a9d...</cas:proxyGrantingTicket><cas:proxies><cas:proxy>proxy1</cas:proxy><cas:proxy>proxy2</cas:proxy><cas:proxy>proxy3</cas:proxy></cas:proxies></cas:authenticationSuccess></cas:serviceResponse>";
server.content = RESPONSE.getBytes(server.encoding);
final Assertion assertion = this.ticketValidator.validate("test",
"test");
final Assertion assertion = this.ticketValidator.validate("test", "test");
assertEquals(USERNAME, assertion.getPrincipal().getName());
}
@Test
public void testProxyChainWithInvalidProxy() throws TicketValidationException,
UnsupportedEncodingException {
public void testProxyChainWithInvalidProxy() throws TicketValidationException, UnsupportedEncodingException {
final String RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'><cas:authenticationSuccess><cas:user>username</cas:user><cas:proxyGrantingTicket>PGTIOU-84678-8a9d...</cas:proxyGrantingTicket><cas:proxies><cas:proxy>proxy7</cas:proxy><cas:proxy>proxy2</cas:proxy><cas:proxy>proxy3</cas:proxy></cas:proxies></cas:authenticationSuccess></cas:serviceResponse>";
server.content = RESPONSE.getBytes(server.encoding);
@ -111,14 +107,15 @@ public final class Cas20ProxyTicketValidatorTests extends AbstractTicketValidato
@Test
public void testConstructionFromSpringBean() throws TicketValidationException, UnsupportedEncodingException {
final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:cas20ProxyTicketValidator.xml");
final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:cas20ProxyTicketValidator.xml");
final Cas20ProxyTicketValidator v = (Cas20ProxyTicketValidator) context.getBean("proxyTicketValidator");
final String USERNAME = "username";
final String RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'><cas:authenticationSuccess><cas:user>username</cas:user><cas:proxyGrantingTicket>PGTIOU-84678-8a9d...</cas:proxyGrantingTicket><cas:proxies><cas:proxy>proxy1</cas:proxy><cas:proxy>proxy2</cas:proxy><cas:proxy>proxy3</cas:proxy></cas:proxies></cas:authenticationSuccess></cas:serviceResponse>";
server.content = RESPONSE.getBytes(server.encoding);
final Assertion assertion = v.validate("test","test");
final Assertion assertion = v.validate("test", "test");
assertEquals(USERNAME, assertion.getPrincipal().getName());
}

View File

@ -17,19 +17,17 @@
* under the License.
*/
package org.jasig.cas.client.validation;
import static org.junit.Assert.*;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.jasig.cas.client.PublicTestHttpServer;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl;
import org.jasig.cas.client.proxy.ProxyRetriever;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.UnsupportedEncodingException;
import java.util.List;
/**
* Test cases for the {@link Cas20ServiceTicketValidator}.
*
@ -72,9 +70,9 @@ public final class Cas20ServiceTicketValidatorTests extends AbstractTicketValida
return new ProxyRetriever() {
/** Unique Id for serialization. */
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public String getProxyTicketIdFor(String proxyGrantingTicketId, String targetService) {
public String getProxyTicketIdFor(String proxyGrantingTicketId, String targetService) {
return "test";
}
};
@ -93,23 +91,19 @@ public final class Cas20ServiceTicketValidatorTests extends AbstractTicketValida
}
@Test
public void testYesResponseButNoPgt() throws TicketValidationException,
UnsupportedEncodingException {
public void testYesResponseButNoPgt() throws TicketValidationException, UnsupportedEncodingException {
final String USERNAME = "username";
final String RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'><cas:authenticationSuccess><cas:user>"
+ USERNAME
+ "</cas:user></cas:authenticationSuccess></cas:serviceResponse>";
+ USERNAME + "</cas:user></cas:authenticationSuccess></cas:serviceResponse>";
server.content = RESPONSE.getBytes(server.encoding);
final Assertion assertion = this.ticketValidator.validate("test",
"test");
final Assertion assertion = this.ticketValidator.validate("test", "test");
assertEquals(USERNAME, assertion.getPrincipal().getName());
}
@Test
public void testYesResponseWithPgt() throws TicketValidationException,
UnsupportedEncodingException {
public void testYesResponseWithPgt() throws TicketValidationException, UnsupportedEncodingException {
final String USERNAME = "username";
final String PGTIOU = "testPgtIou";
final String PGT = "test";
@ -122,23 +116,21 @@ public final class Cas20ServiceTicketValidatorTests extends AbstractTicketValida
server.content = RESPONSE.getBytes(server.encoding);
this.proxyGrantingTicketStorage.save(PGTIOU, PGT);
final Assertion assertion = this.ticketValidator.validate("test",
"test");
final Assertion assertion = this.ticketValidator.validate("test", "test");
assertEquals(USERNAME, assertion.getPrincipal().getName());
// assertEquals(PGT, assertion.getProxyGrantingTicketId());
// assertEquals(PGT, assertion.getProxyGrantingTicketId());
}
@Test
public void testGetAttributes() throws TicketValidationException,
UnsupportedEncodingException {
public void testGetAttributes() throws TicketValidationException, UnsupportedEncodingException {
final String USERNAME = "username";
final String PGTIOU = "testPgtIou";
final String RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'><cas:authenticationSuccess><cas:user>"
+ USERNAME
+ "</cas:user><cas:proxyGrantingTicket>"
+ PGTIOU
+ "</cas:proxyGrantingTicket><cas:attributes><cas:password>test</cas:password><cas:eduPersonId>id</cas:eduPersonId><cas:longAttribute>test1\n\ntest</cas:longAttribute><cas:multivaluedAttribute>value1</cas:multivaluedAttribute><cas:multivaluedAttribute>value2</cas:multivaluedAttribute></cas:attributes></cas:authenticationSuccess></cas:serviceResponse>";
+ USERNAME
+ "</cas:user><cas:proxyGrantingTicket>"
+ PGTIOU
+ "</cas:proxyGrantingTicket><cas:attributes><cas:password>test</cas:password><cas:eduPersonId>id</cas:eduPersonId><cas:longAttribute>test1\n\ntest</cas:longAttribute><cas:multivaluedAttribute>value1</cas:multivaluedAttribute><cas:multivaluedAttribute>value2</cas:multivaluedAttribute></cas:attributes></cas:authenticationSuccess></cas:serviceResponse>";
server.content = RESPONSE.getBytes(server.encoding);
final Assertion assertion = this.ticketValidator.validate("test", "test");
assertEquals(USERNAME, assertion.getPrincipal().getName());
@ -147,7 +139,7 @@ public final class Cas20ServiceTicketValidatorTests extends AbstractTicketValida
assertEquals("test1\n\ntest", assertion.getPrincipal().getAttributes().get("longAttribute"));
try {
List<?> multivalued = (List<?>) assertion.getPrincipal().getAttributes().get("multivaluedAttribute");
assertArrayEquals(new String[]{"value1", "value2"}, multivalued.toArray());
assertArrayEquals(new String[] { "value1", "value2" }, multivalued.toArray());
} catch (Exception e) {
fail("'multivaluedAttribute' attribute expected as List<Object> object.");
}

View File

@ -18,13 +18,12 @@
*/
package org.jasig.cas.client.validation;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockServletContext;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit test for {@link Saml11TicketValidationFilter}.
*

View File

@ -18,17 +18,18 @@
*/
package org.jasig.cas.client.validation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import org.jasig.cas.client.PublicTestHttpServer;
import org.jasig.cas.client.util.CommonUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Interval;
import org.junit.*;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
/**
* @author Scott Battaglia
@ -40,7 +41,7 @@ public final class Saml11TicketValidatorTests extends AbstractTicketValidatorTes
private Saml11TicketValidator validator;
private static final PublicTestHttpServer server = PublicTestHttpServer.instance(9051);
private static final PublicTestHttpServer server = PublicTestHttpServer.instance(9051);
@Before
public void setUp() throws Exception {
@ -55,17 +56,17 @@ public final class Saml11TicketValidatorTests extends AbstractTicketValidatorTes
@Test
public void testCompatibilityValidationFailedResponse() throws UnsupportedEncodingException {
final String RESPONSE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope\n" +
" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><Response\n" +
" xmlns=\"urn:oasis:names:tc:SAML:1.0:protocol\"\n" +
" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\"\n" +
" xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\"\n" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" IssueInstant=\"2008-06-03T04:44:57.143Z\" MajorVersion=\"1\" MinorVersion=\"1\"\n" +
" Recipient=\"http://localhost:8084/WebApplication1/\"\n" +
" ResponseID=\"_3b62bece2e8da1c10279db04882012ac\"><Status><StatusCode\n" +
" Value=\"samlp:Responder\"></StatusCode><StatusMessage>Success</StatusMessage></Status></Response></SOAP-ENV:Body></SOAP-ENV:Envelope>";
final String RESPONSE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope\n"
+ " xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><Response\n"
+ " xmlns=\"urn:oasis:names:tc:SAML:1.0:protocol\"\n"
+ " xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\"\n"
+ " xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\"\n"
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " IssueInstant=\"2008-06-03T04:44:57.143Z\" MajorVersion=\"1\" MinorVersion=\"1\"\n"
+ " Recipient=\"http://localhost:8084/WebApplication1/\"\n"
+ " ResponseID=\"_3b62bece2e8da1c10279db04882012ac\"><Status><StatusCode\n"
+ " Value=\"samlp:Responder\"></StatusCode><StatusMessage>Success</StatusMessage></Status></Response></SOAP-ENV:Body></SOAP-ENV:Envelope>";
server.content = RESPONSE.getBytes(server.encoding);
try {
@ -80,43 +81,61 @@ public final class Saml11TicketValidatorTests extends AbstractTicketValidatorTes
public void testCompatibilityValidationSuccessWithNoAttributes() throws UnsupportedEncodingException {
final Interval range = currentTimeRangeInterval();
final Date now = new Date();
final String RESPONSE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><Response xmlns=\"urn:oasis:names:tc:SAML:1.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\" xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" IssueInstant=\"" + CommonUtils.formatForUtcTime(now) + "\" MajorVersion=\"1\" MinorVersion=\"1\" Recipient=\"test\" ResponseID=\"_e1e2124c08ab456eab0bbab3e1c0c433\"><Status><StatusCode Value=\"samlp:Success\"></StatusCode></Status><Assertion xmlns=\"urn:oasis:names:tc:SAML:1.0:assertion\" AssertionID=\"_d2fd0d6e4da6a6d7d2ba5274ab570d5c\" IssueInstant=\"" + CommonUtils.formatForUtcTime(now) + "\" Issuer=\"testIssuer\" MajorVersion=\"1\" MinorVersion=\"1\"><Conditions NotBefore=\"" + CommonUtils.formatForUtcTime(range.getStart().toDate()) + "\" NotOnOrAfter=\"" + CommonUtils.formatForUtcTime(range.getEnd().toDate()) + "\"><AudienceRestrictionCondition><Audience>test</Audience></AudienceRestrictionCondition></Conditions><AuthenticationStatement AuthenticationInstant=\"2008-06-19T14:34:44.426Z\" AuthenticationMethod=\"urn:ietf:rfc:2246\"><Subject><NameIdentifier>testPrincipal</NameIdentifier><SubjectConfirmation><ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:artifact</ConfirmationMethod></SubjectConfirmation></Subject></AuthenticationStatement></Assertion></Response></SOAP-ENV:Body></SOAP-ENV:Envelope>";
final String RESPONSE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><Response xmlns=\"urn:oasis:names:tc:SAML:1.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\" xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" IssueInstant=\""
+ CommonUtils.formatForUtcTime(now)
+ "\" MajorVersion=\"1\" MinorVersion=\"1\" Recipient=\"test\" ResponseID=\"_e1e2124c08ab456eab0bbab3e1c0c433\"><Status><StatusCode Value=\"samlp:Success\"></StatusCode></Status><Assertion xmlns=\"urn:oasis:names:tc:SAML:1.0:assertion\" AssertionID=\"_d2fd0d6e4da6a6d7d2ba5274ab570d5c\" IssueInstant=\""
+ CommonUtils.formatForUtcTime(now)
+ "\" Issuer=\"testIssuer\" MajorVersion=\"1\" MinorVersion=\"1\"><Conditions NotBefore=\""
+ CommonUtils.formatForUtcTime(range.getStart().toDate())
+ "\" NotOnOrAfter=\""
+ CommonUtils.formatForUtcTime(range.getEnd().toDate())
+ "\"><AudienceRestrictionCondition><Audience>test</Audience></AudienceRestrictionCondition></Conditions><AuthenticationStatement AuthenticationInstant=\"2008-06-19T14:34:44.426Z\" AuthenticationMethod=\"urn:ietf:rfc:2246\"><Subject><NameIdentifier>testPrincipal</NameIdentifier><SubjectConfirmation><ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:artifact</ConfirmationMethod></SubjectConfirmation></Subject></AuthenticationStatement></Assertion></Response></SOAP-ENV:Body></SOAP-ENV:Envelope>";
server.content = RESPONSE.getBytes(server.encoding);
try {
final Assertion a = this.validator.validate("test", "test");
assertEquals("testPrincipal", a.getPrincipal().getName());
} catch (final TicketValidationException e) {
fail(e.toString());
}
try {
final Assertion a = this.validator.validate("test", "test");
assertEquals("testPrincipal", a.getPrincipal().getName());
} catch (final TicketValidationException e) {
fail(e.toString());
}
}
@Test
public void openSaml2GeneratedResponse() throws UnsupportedEncodingException {
final Interval range = currentTimeRangeInterval();
final Date now = new Date();
final String response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soap11:Envelope xmlns:soap11=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap11:Body>"
+ "<saml1p:Response xmlns:saml1p=\"urn:oasis:names:tc:SAML:1.0:protocol\" InResponseTo=\"_fd1632b5dfa921623e7ca6f9ab727161\" IssueInstant=\"" + CommonUtils.formatForUtcTime(now) + "\" MajorVersion=\"1\" MinorVersion=\"1\" Recipient=\"https://example.com/test-client/secure/?TARGET=https%3A%2F%2Fexample.com%2Ftest-client%2Fsecure%2F\" ResponseID=\"_436dbb2cca5166af29250f431a07888f\">"
+ "<saml1p:Status><saml1p:StatusCode Value=\"saml1p:Success\"/></saml1p:Status>"
+ "<saml1:Assertion xmlns:saml1=\"urn:oasis:names:tc:SAML:1.0:assertion\" IssueInstant=\"" + CommonUtils.formatForUtcTime(now) + "\" Issuer=\"localhost\" MajorVersion=\"1\" MinorVersion=\"1\">"
+ "<saml1:Conditions NotBefore=\"" + CommonUtils.formatForUtcTime(range.getStart().toDate()) + "\" NotOnOrAfter=\"" + CommonUtils.formatForUtcTime(range.getEnd().toDate()) + "\">"
+ "<saml1:AudienceRestrictionCondition><saml1:Audience>https://example.com/test-client/secure/</saml1:Audience></saml1:AudienceRestrictionCondition></saml1:Conditions>"
+ "<saml1:AuthenticationStatement AuthenticationInstant=\"" + CommonUtils.formatForUtcTime(now) + "\" AuthenticationMethod=\"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport\">"
+ "<saml1:Subject><saml1:NameIdentifier>testPrincipal</saml1:NameIdentifier><saml1:SubjectConfirmation><saml1:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:artifact</saml1:ConfirmationMethod></saml1:SubjectConfirmation></saml1:Subject></saml1:AuthenticationStatement><saml1:AttributeStatement><saml1:Subject><saml1:NameIdentifier>testPrincipal</saml1:NameIdentifier><saml1:SubjectConfirmation><saml1:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:artifact</saml1:ConfirmationMethod></saml1:SubjectConfirmation></saml1:Subject><saml1:Attribute AttributeName=\"uid\" AttributeNamespace=\"http://www.ja-sig.org/products/cas/\"><saml1:AttributeValue xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:string\">12345</saml1:AttributeValue>"
+ "</saml1:Attribute><saml1:Attribute AttributeName=\"accountState\" AttributeNamespace=\"http://www.ja-sig.org/products/cas/\">"
+ "<saml1:AttributeValue xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:string\">ACTIVE</saml1:AttributeValue>"
+ "</saml1:Attribute><saml1:Attribute AttributeName=\"eduPersonAffiliation\" AttributeNamespace=\"http://www.ja-sig.org/products/cas/\">"
+ "<saml1:AttributeValue xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:string\">employee</saml1:AttributeValue>"
+ "<saml1:AttributeValue xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:string\">staff</saml1:AttributeValue>"
+ "<saml1:AttributeValue xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:string\">student</saml1:AttributeValue></saml1:Attribute></saml1:AttributeStatement></saml1:Assertion></saml1p:Response></soap11:Body></soap11:Envelope>";
+ "<saml1p:Response xmlns:saml1p=\"urn:oasis:names:tc:SAML:1.0:protocol\" InResponseTo=\"_fd1632b5dfa921623e7ca6f9ab727161\" IssueInstant=\""
+ CommonUtils.formatForUtcTime(now)
+ "\" MajorVersion=\"1\" MinorVersion=\"1\" Recipient=\"https://example.com/test-client/secure/?TARGET=https%3A%2F%2Fexample.com%2Ftest-client%2Fsecure%2F\" ResponseID=\"_436dbb2cca5166af29250f431a07888f\">"
+ "<saml1p:Status><saml1p:StatusCode Value=\"saml1p:Success\"/></saml1p:Status>"
+ "<saml1:Assertion xmlns:saml1=\"urn:oasis:names:tc:SAML:1.0:assertion\" IssueInstant=\""
+ CommonUtils.formatForUtcTime(now)
+ "\" Issuer=\"localhost\" MajorVersion=\"1\" MinorVersion=\"1\">"
+ "<saml1:Conditions NotBefore=\""
+ CommonUtils.formatForUtcTime(range.getStart().toDate())
+ "\" NotOnOrAfter=\""
+ CommonUtils.formatForUtcTime(range.getEnd().toDate())
+ "\">"
+ "<saml1:AudienceRestrictionCondition><saml1:Audience>https://example.com/test-client/secure/</saml1:Audience></saml1:AudienceRestrictionCondition></saml1:Conditions>"
+ "<saml1:AuthenticationStatement AuthenticationInstant=\""
+ CommonUtils.formatForUtcTime(now)
+ "\" AuthenticationMethod=\"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport\">"
+ "<saml1:Subject><saml1:NameIdentifier>testPrincipal</saml1:NameIdentifier><saml1:SubjectConfirmation><saml1:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:artifact</saml1:ConfirmationMethod></saml1:SubjectConfirmation></saml1:Subject></saml1:AuthenticationStatement><saml1:AttributeStatement><saml1:Subject><saml1:NameIdentifier>testPrincipal</saml1:NameIdentifier><saml1:SubjectConfirmation><saml1:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:artifact</saml1:ConfirmationMethod></saml1:SubjectConfirmation></saml1:Subject><saml1:Attribute AttributeName=\"uid\" AttributeNamespace=\"http://www.ja-sig.org/products/cas/\"><saml1:AttributeValue xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:string\">12345</saml1:AttributeValue>"
+ "</saml1:Attribute><saml1:Attribute AttributeName=\"accountState\" AttributeNamespace=\"http://www.ja-sig.org/products/cas/\">"
+ "<saml1:AttributeValue xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:string\">ACTIVE</saml1:AttributeValue>"
+ "</saml1:Attribute><saml1:Attribute AttributeName=\"eduPersonAffiliation\" AttributeNamespace=\"http://www.ja-sig.org/products/cas/\">"
+ "<saml1:AttributeValue xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:string\">employee</saml1:AttributeValue>"
+ "<saml1:AttributeValue xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:string\">staff</saml1:AttributeValue>"
+ "<saml1:AttributeValue xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:string\">student</saml1:AttributeValue></saml1:Attribute></saml1:AttributeStatement></saml1:Assertion></saml1p:Response></soap11:Body></soap11:Envelope>";
server.content = response.getBytes(server.encoding);
try {
final Assertion a = this.validator.validate("test", "test");
assertEquals("testPrincipal", a.getPrincipal().getName());
} catch (final TicketValidationException e) {
fail(e.toString());
}
final Assertion a = this.validator.validate("test", "test");
assertEquals("testPrincipal", a.getPrincipal().getName());
} catch (final TicketValidationException e) {
fail(e.toString());
}
}
private Interval currentTimeRangeInterval() {

File diff suppressed because it is too large Load Diff

View File

@ -23,16 +23,15 @@ import com.atlassian.confluence.event.events.security.LoginFailedEvent;
import com.atlassian.confluence.user.ConfluenceAuthenticator;
import com.atlassian.seraph.auth.AuthenticatorException;
import com.atlassian.seraph.auth.LoginReason;
import java.security.Principal;
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.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.Principal;
/**
* Extension of ConfluenceAuthenticator to allow people to configure Confluence 3.5+ to authenticate
* via CAS.
@ -71,13 +70,15 @@ public final class Confluence35CasAuthenticator extends ConfluenceAuthenticator
putPrincipalInSessionContext(request, user);
getElevatedSecurityGuard().onSuccessfulLoginAttempt(request, username);
// Firing this event is necessary to ensure the user's personal information is initialised correctly.
getEventPublisher().publish(new LoginEvent(this, username, request.getSession().getId(), remoteHost, remoteIP));
getEventPublisher().publish(
new LoginEvent(this, username, request.getSession().getId(), remoteHost, remoteIP));
LoginReason.OK.stampRequestResponse(request, response);
LOGGER.debug("Logging in [{}] from CAS.", username);
} else {
LOGGER.debug("Failed logging [{}] from CAS.", username);
getElevatedSecurityGuard().onFailedLoginAttempt(request, username);
getEventPublisher().publish(new LoginFailedEvent(this, username, request.getSession().getId(), remoteHost, remoteIP));
getEventPublisher().publish(
new LoginFailedEvent(this, username, request.getSession().getId(), remoteHost, remoteIP));
}
return user;
}
@ -85,7 +86,8 @@ public final class Confluence35CasAuthenticator extends ConfluenceAuthenticator
return super.getUser(request, response);
}
public boolean logout(final HttpServletRequest request, final HttpServletResponse response) throws AuthenticatorException {
public boolean logout(final HttpServletRequest request, final HttpServletResponse response)
throws AuthenticatorException {
final HttpSession session = request.getSession();
final Principal principal = (Principal) session.getAttribute(LOGGED_IN_KEY);
@ -98,4 +100,4 @@ public final class Confluence35CasAuthenticator extends ConfluenceAuthenticator
session.setAttribute(AbstractCasFilter.CONST_CAS_ASSERTION, null);
return true;
}
}
}

View File

@ -20,16 +20,15 @@ package org.jasig.cas.client.integration.atlassian;
import com.atlassian.confluence.user.ConfluenceAuthenticator;
import com.atlassian.seraph.auth.AuthenticatorException;
import java.security.Principal;
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.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.Principal;
/**
* Extension of ConfluenceAuthenticator to allow people to configure Confluence to authenticate
* via CAS.
@ -70,7 +69,8 @@ public final class ConfluenceCasAuthenticator extends ConfluenceAuthenticator {
return super.getUser(request, response);
}
public boolean logout(final HttpServletRequest request, final HttpServletResponse response) throws AuthenticatorException {
public boolean logout(final HttpServletRequest request, final HttpServletResponse response)
throws AuthenticatorException {
final HttpSession session = request.getSession();
final Principal principal = (Principal) session.getAttribute(LOGGED_IN_KEY);
@ -82,4 +82,4 @@ public final class ConfluenceCasAuthenticator extends ConfluenceAuthenticator {
session.setAttribute(AbstractCasFilter.CONST_CAS_ASSERTION, null);
return true;
}
}
}

View File

@ -21,16 +21,15 @@ package org.jasig.cas.client.integration.atlassian;
import com.atlassian.jira.security.login.JiraSeraphAuthenticator;
import com.atlassian.seraph.auth.AuthenticatorException;
import com.atlassian.seraph.auth.LoginReason;
import java.security.Principal;
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.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.Principal;
/**
* Extension of JiraSeraphAuthenticator to allow people to configure
* JIRA 4.4 and above to authenticate via Jasig CAS
@ -77,7 +76,8 @@ public final class Jira44CasAuthenticator extends JiraSeraphAuthenticator {
return super.getUser(request, response);
}
public boolean logout(final HttpServletRequest request, final HttpServletResponse response) throws AuthenticatorException {
public boolean logout(final HttpServletRequest request, final HttpServletResponse response)
throws AuthenticatorException {
final HttpSession session = request.getSession();
final Principal p = (Principal) session.getAttribute(LOGGED_IN_KEY);
@ -89,4 +89,4 @@ public final class Jira44CasAuthenticator extends JiraSeraphAuthenticator {
session.setAttribute(AbstractCasFilter.CONST_CAS_ASSERTION, null);
return true;
}
}
}

View File

@ -18,20 +18,19 @@
*/
package org.jasig.cas.client.integration.atlassian;
import com.atlassian.seraph.auth.DefaultAuthenticator;
import com.atlassian.seraph.auth.AuthenticatorException;
import com.atlassian.seraph.auth.DefaultAuthenticator;
import com.opensymphony.user.EntityNotFoundException;
import com.opensymphony.user.UserManager;
import java.security.Principal;
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.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.Principal;
/**
* Extension of ConfluenceAuthenticator to allow people to configure Confluence to authenticate
* via CAS.
@ -87,7 +86,8 @@ public final class JiraCasAuthenticator extends DefaultAuthenticator {
return super.getUser(request, response);
}
public boolean logout(final HttpServletRequest request, final HttpServletResponse response) throws AuthenticatorException {
public boolean logout(final HttpServletRequest request, final HttpServletResponse response)
throws AuthenticatorException {
final HttpSession session = request.getSession();
final Principal p = (Principal) session.getAttribute(LOGGED_IN_KEY);
@ -98,4 +98,4 @@ public final class JiraCasAuthenticator extends DefaultAuthenticator {
session.setAttribute(AbstractCasFilter.CONST_CAS_ASSERTION, null);
return true;
}
}
}

View File

@ -1,69 +1,69 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<parent>
<groupId>org.jasig.cas.client</groupId>
<version>3.3-SNAPSHOT</version>
<artifactId>cas-client</artifactId>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.jasig.cas.client</groupId>
<version>3.3-SNAPSHOT</version>
<artifactId>cas-client</artifactId>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-integration-jboss</artifactId>
<packaging>jar</packaging>
<name>Jasig CAS Client for Java - JBoss Integration</name>
<artifactId>cas-client-integration-jboss</artifactId>
<packaging>jar</packaging>
<name>Jasig CAS Client for Java - JBoss Integration</name>
<dependencies>
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependencies>
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<!-- http://repository.jboss.org/maven2/org/jboss/jbossas/jboss-as-tomcat/5.1.0.GA/ -->
<dependency>
<groupId>org.jboss.jbossas</groupId>
<artifactId>jboss-as-tomcat</artifactId>
<version>${jboss.version}</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>trove</groupId>
<artifactId>trove</artifactId>
</exclusion>
<exclusion>
<groupId>apache-log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>jpl-pattern</groupId>
<artifactId>jpl-pattern</artifactId>
</exclusion>
<exclusion>
<groupId>jpl-util</groupId>
<artifactId>jpl-util</artifactId>
</exclusion>
<exclusion>
<groupId>javax.security</groupId>
<artifactId>jacc</artifactId>
</exclusion>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<!-- http://repository.jboss.org/maven2/org/jboss/jbossas/jboss-as-tomcat/5.1.0.GA/ -->
<dependency>
<groupId>org.jboss.jbossas</groupId>
<artifactId>jboss-as-tomcat</artifactId>
<version>${jboss.version}</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>trove</groupId>
<artifactId>trove</artifactId>
</exclusion>
<exclusion>
<groupId>apache-log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>jpl-pattern</groupId>
<artifactId>jpl-pattern</artifactId>
</exclusion>
<exclusion>
<groupId>jpl-util</groupId>
<artifactId>jpl-util</artifactId>
</exclusion>
<exclusion>
<groupId>javax.security</groupId>
<artifactId>jacc</artifactId>
</exclusion>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<!-- This must be disabled before releasing a production-ready version. -->
<repositories>
<repository>
<id>jboss</id>
<name>JBoss Repository</name>
<url>https://repository.jboss.org/nexus/content/groups/public//</url>
</repository>
</repositories>
<properties>
<jboss.version>6.1.0.Final</jboss.version>
</properties>
<!-- This must be disabled before releasing a production-ready version. -->
<repositories>
<repository>
<id>jboss</id>
<name>JBoss Repository</name>
<url>https://repository.jboss.org/nexus/content/groups/public//</url>
</repository>
</repositories>
<properties>
<jboss.version>6.1.0.Final</jboss.version>
</properties>
</project>

View File

@ -20,7 +20,6 @@ package org.jasig.cas.client.jboss.authentication;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
@ -28,11 +27,9 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.jasig.cas.client.jaas.AssertionPrincipal;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.util.CommonUtils;
import org.jboss.web.tomcat.security.login.WebAuthentication;
/**
@ -53,7 +50,8 @@ import org.jboss.web.tomcat.security.login.WebAuthentication;
*/
public final class WebAuthenticationFilter extends AbstractCasFilter {
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain chain) throws IOException, ServletException {
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpServletResponse response = (HttpServletResponse) servletResponse;
final HttpSession session = request.getSession();
@ -73,7 +71,8 @@ public final class WebAuthenticationFilter extends AbstractCasFilter {
request.getSession().setAttribute(CONST_CAS_ASSERTION, principal.getAssertion());
} else {
logger.debug("Aborting -- principal is not of type AssertionPrincipal");
throw new GeneralSecurityException("JBoss Web authentication did not produce CAS AssertionPrincipal.");
throw new GeneralSecurityException(
"JBoss Web authentication did not produce CAS AssertionPrincipal.");
}
} catch (final GeneralSecurityException e) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());

View File

@ -2,26 +2,26 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cas-client</artifactId>
<parent>
<artifactId>cas-client</artifactId>
<groupId>org.jasig.cas.client</groupId>
<version>3.3-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.jasig.cas.client</groupId>
<version>3.3-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cas-client-integration-tomcat-common</artifactId>
<packaging>jar</packaging>
<name>Jasig CAS Client for Java - Common Tomcat Integration Support</name>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-integration-tomcat-common</artifactId>
<packaging>jar</packaging>
<name>Jasig CAS Client for Java - Common Tomcat Integration Support</name>
<dependencies>
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<version>${project.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<version>${project.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@ -21,7 +21,6 @@ package org.jasig.cas.client.tomcat;
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.validation.Assertion;
@ -51,7 +50,8 @@ public abstract class AbstractLogoutHandler implements LogoutHandler {
final Assertion assertion;
final HttpSession httpSession = request.getSession(false);
if (httpSession != null && (assertion = (Assertion) httpSession.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION)) != null) {
if (httpSession != null
&& (assertion = (Assertion) httpSession.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION)) != null) {
httpSession.removeAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
logger.info("Successfully logged out {}", assertion.getPrincipal());
} else {

View File

@ -22,7 +22,6 @@ import java.security.Principal;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.util.CommonUtils;
@ -46,6 +45,7 @@ public class AssertionCasRealmDelegate implements CasRealm {
/** Name of the role attribute in the principal's attributes */
private String roleAttributeName = DEFAULT_ROLE_NAME;
/**
* @param name Name of the attribute in the principal that contains role data.
*/
@ -60,7 +60,8 @@ public class AssertionCasRealmDelegate implements CasRealm {
/** {@inheritDoc} */
public String[] getRoles(final Principal p) {
CommonUtils.assertTrue(p instanceof AttributePrincipal, "Expected instance of AttributePrincipal but got " + p.getClass());
CommonUtils.assertTrue(p instanceof AttributePrincipal,
"Expected instance of AttributePrincipal but got " + p.getClass());
final Collection<String> roles = getRoleCollection(p);
final String[] array = new String[roles.size()];

View File

@ -20,11 +20,9 @@ package org.jasig.cas.client.tomcat;
import java.io.IOException;
import java.security.Principal;
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.validation.Assertion;
@ -51,17 +49,17 @@ public final class AuthenticatorDelegate {
private final Logger logger = LoggerFactory.getLogger(getClass());
private String serviceUrl;
private String serverName;
private String casServerLoginUrl;
private String artifactParameterName;
private String serviceParameterName;
private TicketValidator ticketValidator;
private CasRealm realm;
/**
@ -87,9 +85,11 @@ public final class AuthenticatorDelegate {
if (assertion == null) {
logger.debug("CAS assertion not found in session -- authentication required.");
final String token = request.getParameter(this.artifactParameterName);
final String service = CommonUtils.constructServiceUrl(request, response, this.serviceUrl, this.serverName, this.artifactParameterName, true);
final String service = CommonUtils.constructServiceUrl(request, response, this.serviceUrl, this.serverName,
this.artifactParameterName, true);
if (CommonUtils.isBlank(token)) {
final String redirectUrl = CommonUtils.constructRedirectUrl(this.casServerLoginUrl, this.serviceParameterName, service, false, false);
final String redirectUrl = CommonUtils.constructRedirectUrl(this.casServerLoginUrl,
this.serviceParameterName, service, false, false);
logger.debug("Redirecting to {}", redirectUrl);
CommonUtils.sendRedirect(response, redirectUrl);
return null;
@ -188,9 +188,9 @@ public final class AuthenticatorDelegate {
private void setUnauthorized(final HttpServletResponse response, final String message) {
try {
if (message != null) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
} else {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
} catch (IOException e) {
throw new IllegalStateException("Error setting 403 status.", e);

View File

@ -46,7 +46,7 @@ public interface CasRealm {
* @return Roles for given principal or empty array if none exist.
*/
String[] getRoles(Principal p);
/**
* Determines whether the given principal possesses the given role.
*

View File

@ -24,7 +24,6 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.*;
import org.jasig.cas.client.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -45,17 +44,17 @@ import org.slf4j.LoggerFactory;
* @since 3.1.12
*
*/
public class PropertiesCasRealmDelegate implements CasRealm {
public class PropertiesCasRealmDelegate implements CasRealm {
/** Log instance */
private final Logger logger = LoggerFactory.getLogger(getClass());
/** Path to backing properties file */
private String propertiesFilePath;
/** Map of usernames to roles */
private Map<String, Set<String>> roleMap;
/**
* @param path Path to properties file container username/role data.
*/
@ -70,7 +69,7 @@ public class PropertiesCasRealmDelegate implements CasRealm {
if (!file.isAbsolute()) {
file = new File(System.getProperty("catalina.base"), propertiesFilePath);
}
CommonUtils.assertTrue(file.exists(), "File not found " + file);
CommonUtils.assertTrue(file.exists(), "File not found " + file);
CommonUtils.assertTrue(file.canRead(), "Cannot read " + file);
logger.debug("Loading users/roles from {}", file);
final Properties properties = new Properties();
@ -79,7 +78,7 @@ public class PropertiesCasRealmDelegate implements CasRealm {
} catch (final IOException e) {
throw new IllegalStateException("Error loading users/roles from " + file, e);
}
this.roleMap = new HashMap<String,Set<String>>(properties.size());
this.roleMap = new HashMap<String, Set<String>>(properties.size());
for (final Object key : properties.keySet()) {
final String user = (String) key;

View File

@ -19,9 +19,7 @@
package org.jasig.cas.client.tomcat;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.jasig.cas.client.util.CommonUtils;
/**
@ -52,7 +50,7 @@ public final class RegexUriLogoutHandler extends AbstractLogoutHandler {
CommonUtils.assertNotNull(this.logoutUriRegex, "A logout URI regular expression is required.");
this.logoutUriPattern = Pattern.compile(this.logoutUriRegex);
}
/** {@inheritDoc} */
public boolean isLogoutRequest(final HttpServletRequest request) {
return this.logoutUriPattern.matcher(request.getRequestURI()).matches();

View File

@ -19,7 +19,6 @@
package org.jasig.cas.client.tomcat;
import javax.servlet.http.HttpServletRequest;
import org.jasig.cas.client.util.CommonUtils;
/**

View File

@ -21,9 +21,7 @@ package org.jasig.cas.client.tomcat;
import java.security.Principal;
import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
/**
@ -47,10 +45,10 @@ public class PropertiesCasRealmDelegateTests extends TestCase {
final Principal p = new AttributePrincipalImpl("rosencrantz");
assertTrue(p == realm.authenticate(p));
}
public void testGetRoles() {
final Principal p = new AttributePrincipalImpl("rosencrantz");
final List<String> expected = Arrays.asList(new String[] {"admins", "users"});
final List<String> expected = Arrays.asList(new String[] { "admins", "users" });
final List<String> actual = Arrays.asList(realm.getRoles(p));
assertEquals(expected.size(), actual.size());
@ -58,7 +56,7 @@ public class PropertiesCasRealmDelegateTests extends TestCase {
assertTrue(actual.contains(item));
}
}
public void testHasRole() {
assertTrue(realm.hasRole(new AttributePrincipalImpl("rosencrantz"), "admins"));
assertTrue(realm.hasRole(new AttributePrincipalImpl("rosencrantz"), "users"));

View File

@ -2,41 +2,41 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cas-client</artifactId>
<parent>
<artifactId>cas-client</artifactId>
<groupId>org.jasig.cas.client</groupId>
<version>3.3-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.jasig.cas.client</groupId>
<version>3.3-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cas-client-integration-tomcat-v6</artifactId>
<packaging>jar</packaging>
<name>Jasig CAS Client for Java - Tomcat 6.x Integration</name>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-integration-tomcat-v6</artifactId>
<packaging>jar</packaging>
<name>Jasig CAS Client for Java - Tomcat 6.x Integration</name>
<dependencies>
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-integration-tomcat-common</artifactId>
<version>${project.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>catalina</artifactId>
<version>6.0.29</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependencies>
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-integration-tomcat-common</artifactId>
<version>${project.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>catalina</artifactId>
<version>6.0.29</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<version>${project.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<version>${project.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@ -18,6 +18,8 @@
*/
package org.jasig.cas.client.tomcat.v6;
import java.io.IOException;
import java.security.Principal;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
@ -33,9 +35,6 @@ import org.jasig.cas.client.validation.TicketValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.security.Principal;
/**
* Base authenticator for all authentication protocols supported by CAS.
*
@ -46,7 +45,7 @@ import java.security.Principal;
public abstract class AbstractAuthenticator extends AuthenticatorBase implements LifecycleListener {
protected final Logger logger = LoggerFactory.getLogger(getClass());
private final AuthenticatorDelegate delegate = new AuthenticatorDelegate();
private String casServerUrlPrefix;
@ -89,10 +88,9 @@ public abstract class AbstractAuthenticator extends AuthenticatorBase implements
CommonUtils.assertTrue(realm instanceof CasRealm, "Expected CasRealm but got " + realm.getInfo());
CommonUtils.assertNotNull(this.casServerUrlPrefix, "casServerUrlPrefix cannot be null.");
CommonUtils.assertNotNull(this.delegate.getCasServerLoginUrl(), "casServerLoginUrl cannot be null.");
CommonUtils.assertTrue(
this.delegate.getServerName() != null || this.delegate.getServiceUrl() != null,
CommonUtils.assertTrue(this.delegate.getServerName() != null || this.delegate.getServiceUrl() != null,
"either serverName or serviceUrl must be set.");
this.delegate.setRealm((CasRealm) realm);
this.delegate.setRealm((CasRealm) realm);
} catch (final Exception e) {
throw new LifecycleException(e);
}
@ -146,12 +144,13 @@ public abstract class AbstractAuthenticator extends AuthenticatorBase implements
}
/** {@inheritDoc} */
public final boolean authenticate(final Request request, final Response response, final LoginConfig loginConfig) throws IOException {
public final boolean authenticate(final Request request, final Response response, final LoginConfig loginConfig)
throws IOException {
Principal principal = request.getUserPrincipal();
boolean result = false;
if (principal == null) {
// Authentication sets the response headers for status and redirect if needed
principal = this.delegate.authenticate(request.getRequest(), response);
principal = this.delegate.authenticate(request.getRequest(), response);
if (principal != null) {
register(request, response, principal, getAuthenticationMethod(), null, null);
result = true;
@ -165,7 +164,7 @@ public abstract class AbstractAuthenticator extends AuthenticatorBase implements
/** {@inheritDoc} */
public void lifecycleEvent(final LifecycleEvent event) {
if (AFTER_START_EVENT.equals(event.getType())) {
logger.debug("{} processing lifecycle event {}", getName(), AFTER_START_EVENT);
logger.debug("{} processing lifecycle event {}", getName(), AFTER_START_EVENT);
this.delegate.setTicketValidator(getTicketValidator());
this.delegate.setArtifactParameterName(getArtifactParameterName());
this.delegate.setServiceParameterName(getServiceParameterName());

View File

@ -28,6 +28,7 @@ package org.jasig.cas.client.tomcat.v6;
public abstract class AbstractCasAuthenticator extends AbstractAuthenticator {
private String proxyCallbackUrl;
protected final String getProxyCallbackUrl() {
return this.proxyCallbackUrl;
}

View File

@ -19,7 +19,6 @@
package org.jasig.cas.client.tomcat.v6;
import java.security.Principal;
import org.apache.catalina.realm.RealmBase;
import org.jasig.cas.client.tomcat.CasRealm;
import org.slf4j.Logger;
@ -36,6 +35,7 @@ public abstract class AbstractCasRealm extends RealmBase implements CasRealm {
/** Logger instance */
protected final Logger logger = LoggerFactory.getLogger(getClass());
/** {@inheritDoc} */
public Principal authenticate(final Principal p) {
return getDelegate().authenticate(p);
@ -55,7 +55,7 @@ public abstract class AbstractCasRealm extends RealmBase implements CasRealm {
public String toString() {
return getName();
}
/** {@inheritDoc} */
public String getInfo() {
return getClass().getName() + "/1.0";

View File

@ -38,11 +38,10 @@ public abstract class AbstractLifecycleValve extends ValveBase implements Lifecy
/** Logger instance */
protected final Logger logger = LoggerFactory.getLogger(getClass());
/** Lifecycle listeners */
private LifecycleSupport lifecycle = new LifecycleSupport(this);
/** {@inheritDoc} */
public void addLifecycleListener(final LifecycleListener listener) {
lifecycle.addLifecycleListener(listener);

View File

@ -18,13 +18,12 @@
*/
package org.jasig.cas.client.tomcat.v6;
import java.io.IOException;
import javax.servlet.ServletException;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.jasig.cas.client.tomcat.LogoutHandler;
import javax.servlet.ServletException;
import java.io.IOException;
/**
* Abstract base class for Container-managed log out. Removes the attributes
* from the session.
@ -45,6 +44,6 @@ public abstract class AbstractLogoutValve extends AbstractLifecycleValve {
logger.debug("URI is not a logout request: {}", request.getRequestURI());
getNext().invoke(request, response);
}
protected abstract LogoutHandler getLogoutHandler();
}

View File

@ -35,7 +35,7 @@ import org.jasig.cas.client.tomcat.CasRealm;
public class AssertionCasRealm extends AbstractCasRealm {
private final AssertionCasRealmDelegate delegate = new AssertionCasRealmDelegate();
/** {@inheritDoc} */
public void start() throws LifecycleException {
super.start();

View File

@ -40,7 +40,7 @@ public class Cas10CasAuthenticator extends AbstractCasAuthenticator {
protected TicketValidator getTicketValidator() {
return this.ticketValidator;
}
protected String getAuthenticationMethod() {
return AUTH_METHOD;
}

View File

@ -34,13 +34,13 @@ public final class Cas20CasAuthenticator extends AbstractCasAuthenticator {
public static final String AUTH_METHOD = "CAS20";
private static final String NAME = Cas20CasAuthenticator.class.getName();
private Cas20ServiceTicketValidator ticketValidator;
protected TicketValidator getTicketValidator() {
return this.ticketValidator;
}
protected String getAuthenticationMethod() {
return AUTH_METHOD;
}

Some files were not shown because too many files have changed in this diff Show More