upgraded to the latest CAS Client for Java.  Also upgraded the adapter to the latest CAS version.
This commit is contained in:
Scott Battaglia 2008-03-10 18:33:34 +00:00
parent 8231df4bc1
commit 2735a1f487
33 changed files with 266 additions and 1709 deletions

View File

@ -7,11 +7,86 @@
</parent>
<artifactId>spring-security-cas-adapter</artifactId>
<name>Spring Security - CAS Adapter</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>cas</groupId>
<artifactId>cas-server</artifactId>
<version>3.0.4</version>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-core</artifactId>
<version>3.2</version>
<exclusions>
<exclusion>
<groupId>org.jasig.service</groupId>
<artifactId>person-directory</artifactId>
</exclusion>
<exclusion>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.santuario</groupId>
<artifactId>xmlsec</artifactId>
</exclusion>
<exclusion>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
<exclusion>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</exclusion>
<exclusion>
<groupId>org.opensaml</groupId>
<artifactId>opensaml</artifactId>
</exclusion>
<exclusion>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
</exclusion>
<exclusion>
<groupId>javax.xml</groupId>
<artifactId>xmldsig</artifactId>
</exclusion>
<exclusion>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</exclusion>
<exclusion>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-webflow</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-tiger</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>cas</groupId>
@ -33,4 +108,14 @@
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>jasig-m2</id>
<name>jasig-m2</name>
<url>http://developer.ja-sig.org/maven2</url>
</repository>
</repositories>
</project>

View File

@ -20,17 +20,12 @@ import org.springframework.security.AuthenticationManager;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.inspektr.common.ioc.annotation.NotNull;
import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.handler.AuthenticationHandler;
import org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.springframework.util.Assert;
/**
* <p>Provides JA-SIG CAS 3 authentication by delegating to the Spring Security <code>AuthenticationManager</code>.</p>
* <p>This class would be configured in the <code>webapp/WEB-INF/deployerConfigContext.xml</code> file in the CAS
@ -45,15 +40,9 @@ import org.springframework.util.Assert;
public final class CasAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {
//~ Instance fields ================================================================================================
@NotNull
private AuthenticationManager authenticationManager;
private Log log = LogFactory.getLog(this.getClass());
//~ Methods ========================================================================================================
protected void afterPropertiesSetInternal() throws Exception {
Assert.notNull(this.authenticationManager, "authenticationManager cannot be null.");
}
protected boolean authenticateUsernamePasswordInternal(final UsernamePasswordCredentials credentials)
throws AuthenticationException {
final Authentication authenticationRequest = new UsernamePasswordAuthenticationToken(credentials.getUsername(),

View File

@ -52,24 +52,12 @@ public class CasAuthenticationHandlerTests extends AbstractDependencyInjectionSp
protected void onSetUp() throws Exception {
this.casAuthenticationHandler = new CasAuthenticationHandler();
this.casAuthenticationHandler.setAuthenticationManager(authenticationManager);
this.casAuthenticationHandler.afterPropertiesSet();
}
public void setAuthenticationManager(final AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
public void testAfterPropertiesSet() throws Exception {
this.casAuthenticationHandler.setAuthenticationManager(null);
try {
this.casAuthenticationHandler.afterPropertiesSet();
fail("IllegalArgumenException expected when no AuthenticationManager is set.");
} catch (final IllegalArgumentException e) {
// this is okay
}
}
public void testGracefullyHandlesInvalidInput() {
try {
assertFalse(this.casAuthenticationHandler.authenticate(getCredentialsFor("", "")));

View File

@ -21,6 +21,18 @@
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<optional>true</optional>
</dependency>
</dependency>
<dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-client-core</artifactId>
<version>3.1.1</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>1.3.0</version>
<optional>true</optional>
</dependency>
</dependencies>
</project>

View File

@ -15,6 +15,9 @@
package org.springframework.security.providers.cas;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.TicketValidationException;
import org.jasig.cas.client.validation.TicketValidator;
import org.springframework.security.SpringSecurityMessageSource;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
@ -25,6 +28,7 @@ import org.springframework.security.providers.UsernamePasswordAuthenticationToke
import org.springframework.security.providers.cas.cache.NullStatelessTicketCache;
import org.springframework.security.ui.cas.CasProcessingFilter;
import org.springframework.security.ui.cas.ServiceProperties;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
@ -64,21 +68,21 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia
private UserDetailsService userDetailsService;
private UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker();
private CasProxyDecider casProxyDecider;
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private StatelessTicketCache statelessTicketCache = new NullStatelessTicketCache();
private String key;
private TicketValidator ticketValidator;
private ServiceProperties serviceProperties;
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.userDetailsService, "A userDetailsService must be set");
Assert.notNull(this.ticketValidator, "A ticketValidator must be set");
Assert.notNull(this.casProxyDecider, "A casProxyDecider must be set");
Assert.notNull(this.statelessTicketCache, "A statelessTicketCache must be set");
Assert.hasText(this.key, "A Key is required so CasAuthenticationProvider can identify tokens it previously authenticated");
Assert.notNull(this.messages, "A message source must be set");
Assert.notNull(this.serviceProperties, "serviceProperties is a required field.");
}
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
@ -137,19 +141,16 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia
}
private CasAuthenticationToken authenticateNow(Authentication authentication) throws AuthenticationException {
// Validate
TicketResponse response = ticketValidator.confirmTicketValid(authentication.getCredentials().toString());
// Check proxy list is trusted
this.casProxyDecider.confirmProxyListTrusted(response.getProxyList());
// Lookup user details
UserDetails userDetails = userDetailsService.loadUserByUsername(response.getUser());
userDetailsChecker.check(userDetails);
// Construct CasAuthenticationToken
return new CasAuthenticationToken(this.key, userDetails, authentication.getCredentials(),
userDetails.getAuthorities(), userDetails, response.getProxyList(), response.getProxyGrantingTicketIou());
try {
final Assertion assertion = this.ticketValidator.validate(authentication.getCredentials().toString(), serviceProperties.getService());
final UserDetails userDetails = userDetailsService.loadUserByUsername(assertion.getPrincipal().getName());
userDetailsChecker.check(userDetails);
return new CasAuthenticationToken(this.key, userDetails, authentication.getCredentials(),
userDetails.getAuthorities(), userDetails, assertion);
} catch (final TicketValidationException e) {
// TODO get error message
throw new BadCredentialsException("", e);
}
}
protected UserDetailsService getUserDetailsService() {
@ -159,13 +160,9 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
public CasProxyDecider getCasProxyDecider() {
return casProxyDecider;
}
public void setCasProxyDecider(CasProxyDecider casProxyDecider) {
this.casProxyDecider = casProxyDecider;
public void setServiceProperties(final ServiceProperties serviceProperties) {
this.serviceProperties = serviceProperties;
}
protected String getKey() {
@ -196,7 +193,7 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia
this.ticketValidator = ticketValidator;
}
public boolean supports(Class authentication) {
public boolean supports(final Class authentication) {
if (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)) {
return true;
} else if (CasAuthenticationToken.class.isAssignableFrom(authentication)) {

View File

@ -15,6 +15,7 @@
package org.springframework.security.providers.cas;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.providers.AbstractAuthenticationToken;
@ -23,25 +24,22 @@ import org.springframework.security.userdetails.UserDetails;
import java.io.Serializable;
import java.util.List;
/**
* Represents a successful CAS <code>Authentication</code>.
*
* @author Ben Alex
* @author Scott Battaglia
* @version $Id$
*/
public class CasAuthenticationToken extends AbstractAuthenticationToken implements Serializable {
//~ Instance fields ================================================================================================
private static final long serialVersionUID = 1L;
private final List proxyList;
private final Object credentials;
private final Object principal;
private final String proxyGrantingTicketIou;
private final UserDetails userDetails;
private final int keyHash;
private final Assertion assertion;
//~ Constructors ===================================================================================================
@ -57,22 +55,17 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
* org.springframework.security.userdetails.UserDetailsService}) (cannot be <code>null</code>)
* @param userDetails the user details (from the {@link
* org.springframework.security.userdetails.UserDetailsService}) (cannot be <code>null</code>)
* @param proxyList the list of proxies from CAS (cannot be
* <code>null</code>)
* @param proxyGrantingTicketIou the PGT-IOU ID from CAS (cannot be
* <code>null</code>, but may be an empty <code>String</code> if no
* PGT-IOU ID was provided)
* @param assertion the assertion returned from the CAS servers. It contains the principal and how to obtain a
* proxy ticket for the user.
*
* @throws IllegalArgumentException if a <code>null</code> was passed
*/
public CasAuthenticationToken(final String key, final Object principal, final Object credentials,
final GrantedAuthority[] authorities, final UserDetails userDetails, final List proxyList,
final String proxyGrantingTicketIou) {
final GrantedAuthority[] authorities, final UserDetails userDetails, final Assertion assertion) {
super(authorities);
if ((key == null) || ("".equals(key)) || (principal == null) || "".equals(principal) || (credentials == null)
|| "".equals(credentials) || (authorities == null) || (userDetails == null) || (proxyList == null)
|| (proxyGrantingTicketIou == null)) {
|| "".equals(credentials) || (authorities == null) || (userDetails == null) || (assertion == null)) {
throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
}
@ -80,8 +73,7 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
this.principal = principal;
this.credentials = credentials;
this.userDetails = userDetails;
this.proxyList = proxyList;
this.proxyGrantingTicketIou = proxyGrantingTicketIou;
this.assertion = assertion;
setAuthenticated(true);
}
@ -94,15 +86,9 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
if (obj instanceof CasAuthenticationToken) {
CasAuthenticationToken test = (CasAuthenticationToken) obj;
// proxyGrantingTicketIou is never null due to constructor
if (!this.getProxyGrantingTicketIou().equals(test.getProxyGrantingTicketIou())) {
return false;
}
// proxyList is never null due to constructor
if (!this.getProxyList().equals(test.getProxyList())) {
return false;
if (!this.assertion.equals(test.getAssertion())) {
return false;
}
if (this.getKeyHash() != test.getKeyHash()) {
@ -127,18 +113,8 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
return this.principal;
}
/**
* Obtains the proxy granting ticket IOU.
*
* @return the PGT IOU-ID or an empty <code>String</code> if no proxy callback was requested when validating the
* service ticket
*/
public String getProxyGrantingTicketIou() {
return proxyGrantingTicketIou;
}
public List getProxyList() {
return proxyList;
public Assertion getAssertion() {
return this.assertion;
}
public UserDetails getUserDetails() {
@ -148,9 +124,8 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(super.toString());
sb.append("; Credentials (Service/Proxy Ticket): ").append(this.credentials);
sb.append("; Proxy-Granting Ticket IOU: ").append(this.proxyGrantingTicketIou);
sb.append("; Proxy List: ").append(this.proxyList);
sb.append(" Assertion: ").append(this.assertion);
sb.append(" Credentials (Service/Proxy Ticket): ").append(this.credentials);
return (sb.toString());
}

View File

@ -1,73 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas;
import java.util.List;
/**
* Decides whether a proxy list presented via CAS is trusted or not.
*
* <p>
* CAS 1.0 allowed services to receive a service ticket and then validate it.
* CAS 2.0 allows services to receive a service ticket and then validate it
* with a proxy callback URL. The callback will enable the CAS server to
* authenticate the service. In doing so the service will receive a
* proxy-granting ticket and a proxy-granting ticket IOU. The IOU is just an
* internal record that a proxy-granting ticket is due to be received via the
* callback URL.
* </p>
*
* <p>
* With a proxy-granting ticket, a service can request the CAS server provides
* it with a proxy ticket. A proxy ticket is just a service ticket, but the
* CAS server internally tracks the list (chain) of services used to build the
* proxy ticket. The proxy ticket is then presented to the target service.
* </p>
*
* <p>
* If this application is a target service of a proxy ticket, the
* <code>CasProxyDecider</code> resolves whether or not the proxy list is
* trusted. Applications should only trust services they allow to impersonate
* an end user.
* </p>
*
* <p>
* If this application is a service that should never accept proxy-granting
* tickets, the implementation should reject tickets that present a proxy list
* with any members. If the list has no members, it indicates the CAS server
* directly authenticated the user (ie there are no services which proxied the
* user authentication).
* </p>
*
* @author Ben Alex
* @version $Id$
*/
public interface CasProxyDecider {
//~ Methods ========================================================================================================
/**
* Decides whether the proxy list is trusted.
* <p>Must throw any <code>ProxyUntrustedException</code> if the
* proxy list is untrusted.</p>
*
* @param proxyList the list of proxies to be checked.
*
* @throws ProxyUntrustedException DOCUMENT ME!
*/
void confirmProxyListTrusted(List proxyList)
throws ProxyUntrustedException;
}

View File

@ -1,50 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas;
import org.springframework.security.AuthenticationException;
/**
* Thrown if a CAS proxy ticket is presented from an untrusted proxy.
*
* @author Ben Alex
* @version $Id$
*/
public class ProxyUntrustedException extends AuthenticationException {
//~ Constructors ===================================================================================================
/**
* Constructs a <code>ProxyUntrustedException</code> with the specified
* message.
*
* @param msg the detail message.
*/
public ProxyUntrustedException(String msg) {
super(msg);
}
/**
* Constructs a <code>ProxyUntrustedException</code> with the specified
* message and root cause.
*
* @param msg the detail message.
* @param t root cause
*/
public ProxyUntrustedException(String msg, Throwable t) {
super(msg, t);
}
}

View File

@ -1,96 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas;
import java.util.List;
import java.util.Vector;
/**
* Represents a CAS service ticket in native CAS form.
*
* @author Ben Alex
* @version $Id$
*/
public class TicketResponse {
//~ Instance fields ================================================================================================
private List proxyList;
private String proxyGrantingTicketIou;
private String user;
//~ Constructors ===================================================================================================
/**
* Constructor.
*
* <P>
* If <code>null</code> is passed into the <code>proxyList</code> or
* <code>proxyGrantingTicketIou</code>, suitable defaults are established.
* However, <code>null</code> cannot be passed for the <code>user</code>
* argument.
* </p>
*
* @param user the user as indicated by CAS (cannot be <code>null</code> or
* an empty <code>String</code>)
* @param proxyList as provided by CAS (may be <code>null</code>)
* @param proxyGrantingTicketIou as provided by CAS (may be
* <code>null</code>)
*
* @throws IllegalArgumentException DOCUMENT ME!
*/
public TicketResponse(String user, List proxyList, String proxyGrantingTicketIou) {
if (proxyList == null) {
proxyList = new Vector();
}
if (proxyGrantingTicketIou == null) {
proxyGrantingTicketIou = "";
}
if ((user == null) || "".equals(user)) {
throw new IllegalArgumentException("Cannot pass null or empty String for User");
}
this.user = user;
this.proxyList = proxyList;
this.proxyGrantingTicketIou = proxyGrantingTicketIou;
}
//~ Methods ========================================================================================================
public String getProxyGrantingTicketIou() {
return proxyGrantingTicketIou;
}
public List getProxyList() {
return proxyList;
}
public String getUser() {
return user;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(super.toString());
sb.append(": User: " + this.user);
sb.append("; Proxy-Granting Ticket IOU: " + this.proxyGrantingTicketIou);
sb.append("; Proxy List: " + this.proxyList.toString());
return sb.toString();
}
}

View File

@ -1,53 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas;
import org.springframework.security.AuthenticationException;
/**
* Validates a CAS service ticket.
*
* <p>
* Implementations must accept CAS proxy tickets, in addition to CAS service
* tickets. If proxy tickets should be rejected, this is resolved by a {@link
* CasProxyDecider} implementation (not by the <code>TicketValidator</code>).
* </p>
*
* <p>
* Implementations may request a proxy granting ticket if wish, although this
* behaviour is not mandatory.
* </p>
*
* @author Ben Alex
* @version $Id$
*/
public interface TicketValidator {
//~ Methods ========================================================================================================
/**
* Returns information about the ticket, if it is valid for this service.<P>Must throw an
* <code>AuthenticationException</code> if the ticket is not valid for this service.</p>
*
* @param serviceTicket DOCUMENT ME!
*
* @return details of the CAS service ticket
*
* @throws AuthenticationException DOCUMENT ME!
*/
TicketResponse confirmTicketValid(String serviceTicket)
throws AuthenticationException;
}

View File

@ -1,51 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas.proxy;
import org.springframework.security.providers.cas.CasProxyDecider;
import org.springframework.security.providers.cas.ProxyUntrustedException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import java.util.List;
/**
* Accepts a proxied request from any other service.<P>Also accepts the request if there was no proxy (ie the user
* directly authenticated against this service).</p>
*
* @author Ben Alex
* @version $Id$
*/
public class AcceptAnyCasProxy implements CasProxyDecider {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(AcceptAnyCasProxy.class);
//~ Methods ========================================================================================================
public void confirmProxyListTrusted(List proxyList)
throws ProxyUntrustedException {
Assert.notNull(proxyList, "proxyList cannot be null");
if (logger.isDebugEnabled()) {
logger.debug("Always accepting proxy list: " + proxyList.toString());
}
}
}

View File

@ -1,88 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas.proxy;
import org.springframework.security.SpringSecurityMessageSource;
import org.springframework.security.providers.cas.CasProxyDecider;
import org.springframework.security.providers.cas.ProxyUntrustedException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.util.Assert;
import java.util.List;
/**
* Accepts proxied requests if the closest proxy is named in the <code>validProxies</code> list.<P>Also accepts the
* request if there was no proxy (ie the user directly authenticated against this service).</p>
*/
public class NamedCasProxyDecider implements CasProxyDecider, InitializingBean, MessageSourceAware {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(NamedCasProxyDecider.class);
//~ Instance fields ================================================================================================
private List validProxies;
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.validProxies, "A validProxies list must be set");
Assert.notNull(this.messages, "A message source must be set");
}
public void confirmProxyListTrusted(List proxyList)
throws ProxyUntrustedException {
Assert.notNull(proxyList, "proxyList cannot be null");
if (logger.isDebugEnabled()) {
logger.debug("Proxy list: " + proxyList.toString());
}
if (proxyList.size() == 0) {
// A Service Ticket (not a Proxy Ticket)
return;
}
if (!validProxies.contains(proxyList.get(0))) {
throw new ProxyUntrustedException(messages.getMessage("NamedCasProxyDecider.untrusted",
new Object[] {proxyList.get(0)}, "Nearest proxy {0} is untrusted"));
}
}
public List getValidProxies() {
return validProxies;
}
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
public void setValidProxies(List validProxies) {
this.validProxies = validProxies;
}
}

View File

@ -1,76 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas.proxy;
import org.springframework.security.SpringSecurityMessageSource;
import org.springframework.security.providers.cas.CasProxyDecider;
import org.springframework.security.providers.cas.ProxyUntrustedException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.util.Assert;
import java.util.List;
/**
* Accepts no proxied requests.<P>This class should be used if only service tickets wish to be accepted (ie no
* proxy tickets at all).</p>
*/
public class RejectProxyTickets implements CasProxyDecider, MessageSourceAware, InitializingBean {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(RejectProxyTickets.class);
//~ Instance fields ================================================================================================
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.messages, "A message source must be set");
}
public void confirmProxyListTrusted(List proxyList)
throws ProxyUntrustedException {
Assert.notNull(proxyList, "proxyList cannot be null");
if (proxyList.size() == 0) {
// A Service Ticket (not a Proxy Ticket)
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Proxies are unacceptable; proxy list provided: " + proxyList.toString());
}
throw new ProxyUntrustedException(
messages.getMessage("RejectProxyTickets.reject", "Proxy tickets are rejected"));
}
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
}

View File

@ -1,6 +0,0 @@
<html>
<body>
Implementations that decide whether proxy lists of
CAS authentications are trusted.
</body>
</html>

View File

@ -1,114 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas.ticketvalidator;
import org.springframework.security.providers.cas.TicketValidator;
import org.springframework.security.ui.cas.ServiceProperties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.io.File;
/**
* Convenience abstract base for <code>TicketValidator</code>s.
*
* @author Ben Alex
* @version $Id$
*/
public abstract class AbstractTicketValidator implements TicketValidator, InitializingBean {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(AbstractTicketValidator.class);
//~ Instance fields ================================================================================================
private ServiceProperties serviceProperties;
private String casValidate;
private String trustStore;
private String trustPassword;
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
Assert.hasLength(casValidate, "A casValidate URL must be set");
Assert.notNull(serviceProperties, "serviceProperties must be specified");
if (StringUtils.hasLength(trustStore)) {
logger.info("Setting system property 'javax.net.ssl.trustStore' to value [" + trustStore + "]");
if (! (new File(trustStore)).exists()) {
throw new IllegalArgumentException("Parameter 'trustStore' file does not exist at " + trustStore);
}
System.setProperty("javax.net.ssl.trustStore", trustStore);
}
if (StringUtils.hasLength(trustPassword)) {
System.setProperty("javax.net.ssl.trustStorePassword", trustPassword);
}
}
/**
* Mandatory URL to CAS' proxy ticket valiation service.<P>This is usually something like
* <code>https://www.mycompany.com/cas/proxyValidate</code>.</p>
*
* @return the CAS proxy ticket validation URL
*/
public String getCasValidate() {
return casValidate;
}
public ServiceProperties getServiceProperties() {
return serviceProperties;
}
/**
* Optional property which will be used to set the system property <code>javax.net.ssl.trustStore</code>.
*
* @return the <code>javax.net.ssl.trustStore</code> that will be set during bean initialization, or
* <code>null</code> to leave the system property unchanged
*/
public String getTrustStore() {
return trustStore;
}
public void setCasValidate(String casValidate) {
this.casValidate = casValidate;
}
public void setServiceProperties(ServiceProperties serviceProperties) {
this.serviceProperties = serviceProperties;
}
public void setTrustStore(String trustStore) {
this.trustStore = trustStore;
}
/**
* Optional property which causes the system property <tt>javax.net.ssl.trustStorePassword</tt> to be set.
*
* @param trustPassword
*/
public void setTrustPassword(String trustPassword) {
this.trustPassword = trustPassword;
}
}

View File

@ -1,116 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas.ticketvalidator;
import edu.yale.its.tp.cas.client.ProxyTicketValidator;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationServiceException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.providers.cas.TicketResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Uses CAS' <code>ProxyTicketValidator</code> to validate a service ticket.
*
* @author Ben Alex
* @version $Id$
*/
public class CasProxyTicketValidator extends AbstractTicketValidator {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(CasProxyTicketValidator.class);
//~ Instance fields ================================================================================================
private String proxyCallbackUrl;
//~ Methods ========================================================================================================
public TicketResponse confirmTicketValid(String serviceTicket)
throws AuthenticationException {
// Attempt to validate presented ticket using CAS' ProxyTicketValidator class
ProxyTicketValidator pv = new ProxyTicketValidator();
pv.setCasValidateUrl(super.getCasValidate());
pv.setServiceTicket(serviceTicket);
pv.setService(super.getServiceProperties().getService());
if (super.getServiceProperties().isSendRenew()) {
logger.warn(
"The current CAS ProxyTicketValidator does not support the 'renew' property. "
+ "The ticket cannot be validated as having been issued by a 'renew' authentication. "
+ "It is expected this will be corrected in a future version of CAS' ProxyTicketValidator.");
}
if ((this.proxyCallbackUrl != null) && (!"".equals(this.proxyCallbackUrl))) {
pv.setProxyCallbackUrl(proxyCallbackUrl);
}
return validateNow(pv);
}
/**
* Optional callback URL to obtain a proxy-granting ticket from CAS.
* <p>This callback URL belongs to the Spring Security secured application. We suggest you use
* CAS' <code>ProxyTicketReceptor</code> servlet to receive this callback and manage the proxy-granting ticket list.
* The callback URL is usually something like
* <code>https://www.mycompany.com/application/casProxy/receptor</code>.
* </p>
* <p>If left <code>null</code>, the <code>CasAuthenticationToken</code> will not have a proxy granting
* ticket IOU and there will be no proxy-granting ticket callback. Accordingly, the Spring Securty
* secured application will be unable to obtain a proxy ticket to call another CAS-secured service on
* behalf of the user. This is not really an issue for most applications.</p>
*
* @return the proxy callback URL, or <code>null</code> if not used
*/
public String getProxyCallbackUrl() {
return proxyCallbackUrl;
}
public void setProxyCallbackUrl(String proxyCallbackUrl) {
this.proxyCallbackUrl = proxyCallbackUrl;
}
/**
* Perform the actual remote invocation. Protected to enable replacement during tests.
*
* @param pv the populated <code>ProxyTicketValidator</code>
*
* @return the <code>TicketResponse</code>
*
* @throws AuthenticationServiceException if<code>ProxyTicketValidator</code> internally fails
* @throws BadCredentialsException DOCUMENT ME!
*/
protected TicketResponse validateNow(ProxyTicketValidator pv)
throws AuthenticationServiceException, BadCredentialsException {
try {
pv.validate();
} catch (Exception internalProxyTicketValidatorProblem) {
throw new AuthenticationServiceException(internalProxyTicketValidatorProblem.getMessage());
}
if (!pv.isAuthenticationSuccesful()) {
throw new BadCredentialsException(pv.getErrorCode() + ": " + pv.getErrorMessage());
}
return new TicketResponse(pv.getUser(), pv.getProxyList(), pv.getPgtIou());
}
}

View File

@ -1,5 +0,0 @@
<html>
<body>
Implementations that validate service tickets.
</body>
</html>

View File

@ -59,9 +59,9 @@ public class CasProcessingFilter extends AbstractProcessingFilter {
//~ Methods ========================================================================================================
public Authentication attemptAuthentication(HttpServletRequest request)
public Authentication attemptAuthentication(final HttpServletRequest request)
throws AuthenticationException {
String username = CAS_STATEFUL_IDENTIFIER;
final String username = CAS_STATEFUL_IDENTIFIER;
String password = request.getParameter("ticket");
if (password == null) {

View File

@ -16,14 +16,13 @@
package org.springframework.security.ui.cas;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jasig.cas.client.util.CommonUtils;
import org.springframework.security.AuthenticationException;
import org.springframework.security.ui.AuthenticationEntryPoint;
import org.springframework.beans.factory.InitializingBean;
@ -39,6 +38,7 @@ import org.springframework.util.Assert;
* which will validate the CAS login was successful.</p>
*
* @author Ben Alex
* @author Scott Battaglia
* @version $Id$
*/
public class CasProcessingFilterEntryPoint implements AuthenticationEntryPoint, InitializingBean {
@ -67,20 +67,11 @@ public class CasProcessingFilterEntryPoint implements AuthenticationEntryPoint,
public void commence(final ServletRequest servletRequest, final ServletResponse servletResponse,
final AuthenticationException authenticationException)
throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpServletResponse response = (HttpServletResponse) servletResponse;
final String urlEncodedService = this.encodeServiceUrlWithSessionId ? response.encodeURL(this.serviceProperties.getService()) : this.serviceProperties.getService();
final String urlEncodedService = CommonUtils.constructServiceUrl(null, response, this.serviceProperties.getService(), null, "ticket", this.encodeServiceUrlWithSessionId);
final String redirectUrl = CommonUtils.constructRedirectUrl(this.loginUrl, "service", urlEncodedService, this.serviceProperties.isSendRenew(), false);
final StringBuffer buffer = new StringBuffer(255);
synchronized (buffer) {
buffer.append(this.loginUrl);
buffer.append("?service=");
buffer.append(URLEncoder.encode(urlEncodedService, "UTF-8"));
buffer.append(this.serviceProperties.isSendRenew() ? "&renew=true" : "");
}
response.sendRedirect(buffer.toString());
response.sendRedirect(redirectUrl);
}
/**

View File

@ -16,6 +16,7 @@
package org.springframework.security.ui.cas;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
/**
@ -36,9 +37,7 @@ public class ServiceProperties implements InitializingBean {
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
if ((service == null) || "".equals(service)) {
throw new IllegalArgumentException("service must be specified");
}
Assert.hasLength(this.service, "service must be specified.");
}
/**

View File

@ -23,19 +23,21 @@ import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.providers.TestingAuthenticationToken;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.providers.cas.ticketvalidator.AbstractTicketValidator;
import org.springframework.security.ui.cas.CasProcessingFilter;
import org.springframework.security.ui.cas.ServiceProperties;
import org.springframework.security.userdetails.User;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.AssertionImpl;
import org.jasig.cas.client.validation.TicketValidationException;
import org.jasig.cas.client.validation.TicketValidator;
import org.junit.Test;
import static org.junit.Assert.*;
@ -44,6 +46,7 @@ import static org.junit.Assert.*;
* Tests {@link CasAuthenticationProvider}.
*
* @author Ben Alex
* @author Scott Battaglia
* @version $Id$
*/
public class CasAuthenticationProviderTests {
@ -58,16 +61,25 @@ public class CasAuthenticationProviderTests {
return new User("user", "password", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B")});
}
private ServiceProperties makeServiceProperties() {
final ServiceProperties serviceProperties = new ServiceProperties();
serviceProperties.setSendRenew(false);
serviceProperties.setService("http://test.com");
return serviceProperties;
}
@Test
public void statefulAuthenticationIsSuccessful() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setUserDetailsService(new MockAuthoritiesPopulator());
cap.setCasProxyDecider(new MockProxyDecider(true));
cap.setKey("qwerty");
StatelessTicketCache cache = new MockStatelessTicketCache();
cap.setStatelessTicketCache(cache);
cap.setServiceProperties(makeServiceProperties());
cap.setTicketValidator(new MockTicketValidator(true));
cap.afterPropertiesSet();
@ -86,9 +98,6 @@ public class CasAuthenticationProviderTests {
CasAuthenticationToken casResult = (CasAuthenticationToken) result;
assertEquals(makeUserDetailsFromAuthoritiesPopulator(), casResult.getPrincipal());
assertEquals("PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt",
casResult.getProxyGrantingTicketIou());
assertEquals("https://localhost/portal/j_spring_cas_security_check", casResult.getProxyList().get(0));
assertEquals("ST-123", casResult.getCredentials());
assertEquals(new GrantedAuthorityImpl("ROLE_A"), casResult.getAuthorities()[0]);
assertEquals(new GrantedAuthorityImpl("ROLE_B"), casResult.getAuthorities()[1]);
@ -107,12 +116,12 @@ public class CasAuthenticationProviderTests {
public void statelessAuthenticationIsSuccessful() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setUserDetailsService(new MockAuthoritiesPopulator());
cap.setCasProxyDecider(new MockProxyDecider(true));
cap.setKey("qwerty");
StatelessTicketCache cache = new MockStatelessTicketCache();
cap.setStatelessTicketCache(cache);
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATELESS_IDENTIFIER,
@ -146,12 +155,12 @@ public class CasAuthenticationProviderTests {
public void missingTicketIdIsDetected() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setUserDetailsService(new MockAuthoritiesPopulator());
cap.setCasProxyDecider(new MockProxyDecider(true));
cap.setKey("qwerty");
StatelessTicketCache cache = new MockStatelessTicketCache();
cap.setStatelessTicketCache(cache);
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token =
@ -162,18 +171,19 @@ public class CasAuthenticationProviderTests {
@Test(expected = BadCredentialsException.class)
public void invalidKeyIsDetected() throws Exception {
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setUserDetailsService(new MockAuthoritiesPopulator());
cap.setCasProxyDecider(new MockProxyDecider(true));
cap.setKey("qwerty");
StatelessTicketCache cache = new MockStatelessTicketCache();
cap.setStatelessTicketCache(cache);
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
CasAuthenticationToken token = new CasAuthenticationToken("WRONG_KEY", makeUserDetails(), "credentials",
new GrantedAuthority[] {new GrantedAuthorityImpl("XX")}, makeUserDetails(), new Vector(), "IOU-xxx");
new GrantedAuthority[] {new GrantedAuthorityImpl("XX")}, makeUserDetails(), assertion);
cap.authenticate(token);
}
@ -181,10 +191,10 @@ public class CasAuthenticationProviderTests {
@Test(expected = IllegalArgumentException.class)
public void detectsMissingAuthoritiesPopulator() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setCasProxyDecider(new MockProxyDecider());
cap.setKey("qwerty");
cap.setStatelessTicketCache(new MockStatelessTicketCache());
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
}
@ -192,19 +202,9 @@ public class CasAuthenticationProviderTests {
public void detectsMissingKey() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setUserDetailsService(new MockAuthoritiesPopulator());
cap.setCasProxyDecider(new MockProxyDecider());
cap.setStatelessTicketCache(new MockStatelessTicketCache());
cap.setTicketValidator(new MockTicketValidator(true));
cap.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void detectsMissingProxyDecider() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty");
cap.setStatelessTicketCache(new MockStatelessTicketCache());
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
}
@ -214,9 +214,9 @@ public class CasAuthenticationProviderTests {
// set this explicitly to null to test failure
cap.setStatelessTicketCache(null);
cap.setUserDetailsService(new MockAuthoritiesPopulator());
cap.setCasProxyDecider(new MockProxyDecider());
cap.setKey("qwerty");
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
}
@ -224,9 +224,9 @@ public class CasAuthenticationProviderTests {
public void detectsMissingTicketValidator() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setUserDetailsService(new MockAuthoritiesPopulator());
cap.setCasProxyDecider(new MockProxyDecider(true));
cap.setKey("qwerty");
cap.setStatelessTicketCache(new MockStatelessTicketCache());
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
}
@ -234,14 +234,13 @@ public class CasAuthenticationProviderTests {
public void gettersAndSettersMatch() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setUserDetailsService(new MockAuthoritiesPopulator());
cap.setCasProxyDecider(new MockProxyDecider());
cap.setKey("qwerty");
cap.setStatelessTicketCache(new MockStatelessTicketCache());
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
assertTrue(cap.getUserDetailsService() != null);
assertTrue(cap.getCasProxyDecider() != null);
assertEquals("qwerty", cap.getKey());
assertTrue(cap.getStatelessTicketCache() != null);
assertTrue(cap.getTicketValidator() != null);
@ -251,10 +250,10 @@ public class CasAuthenticationProviderTests {
public void ignoresClassesItDoesNotSupport() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setUserDetailsService(new MockAuthoritiesPopulator());
cap.setCasProxyDecider(new MockProxyDecider());
cap.setKey("qwerty");
cap.setStatelessTicketCache(new MockStatelessTicketCache());
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password",
@ -269,10 +268,10 @@ public class CasAuthenticationProviderTests {
public void ignoresUsernamePasswordAuthenticationTokensWithoutCasIdentifiersAsPrincipal() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setUserDetailsService(new MockAuthoritiesPopulator());
cap.setCasProxyDecider(new MockProxyDecider());
cap.setKey("qwerty");
cap.setStatelessTicketCache(new MockStatelessTicketCache());
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("some_normal_user",
@ -295,27 +294,6 @@ public class CasAuthenticationProviderTests {
}
}
private class MockProxyDecider implements CasProxyDecider {
private boolean acceptProxy;
public MockProxyDecider(boolean acceptProxy) {
this.acceptProxy = acceptProxy;
}
private MockProxyDecider() {
super();
}
public void confirmProxyListTrusted(List proxyList)
throws ProxyUntrustedException {
if (acceptProxy) {
return;
} else {
throw new ProxyUntrustedException("As requested from mock");
}
}
}
private class MockStatelessTicketCache implements StatelessTicketCache {
private Map cache = new HashMap();
@ -336,23 +314,19 @@ public class CasAuthenticationProviderTests {
}
}
private class MockTicketValidator extends AbstractTicketValidator {
private class MockTicketValidator implements TicketValidator {
private boolean returnTicket;
public MockTicketValidator(boolean returnTicket) {
this.returnTicket = returnTicket;
}
public TicketResponse confirmTicketValid(String serviceTicket)
throws AuthenticationException {
if (returnTicket) {
List list = new Vector();
list.add("https://localhost/portal/j_spring_cas_security_check");
return new TicketResponse("rod", list, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
}
throw new BadCredentialsException("As requested from mock");
}
public Assertion validate(final String ticket, final String service)
throws TicketValidationException {
if (returnTicket) {
return new AssertionImpl("rod");
}
throw new BadCredentialsException("As requested from mock");
}
}
}

View File

@ -17,6 +17,8 @@ package org.springframework.security.providers.cas;
import junit.framework.TestCase;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.AssertionImpl;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
@ -25,10 +27,6 @@ import org.springframework.security.providers.UsernamePasswordAuthenticationToke
import org.springframework.security.userdetails.User;
import org.springframework.security.userdetails.UserDetails;
import java.util.List;
import java.util.Vector;
/**
* Tests {@link CasAuthenticationToken}.
*
@ -66,10 +64,11 @@ public class CasAuthenticationTokenTests extends TestCase {
}
public void testConstructorRejectsNulls() {
final Assertion assertion = new AssertionImpl("test");
try {
new CasAuthenticationToken(null, makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
@ -78,7 +77,7 @@ public class CasAuthenticationTokenTests extends TestCase {
try {
new CasAuthenticationToken("key", null, "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
@ -87,15 +86,14 @@ public class CasAuthenticationTokenTests extends TestCase {
try {
new CasAuthenticationToken("key", makeUserDetails(), null,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", null, makeUserDetails(), new Vector(),
"PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
new CasAuthenticationToken("key", makeUserDetails(), "Password", null, makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
@ -104,7 +102,7 @@ public class CasAuthenticationTokenTests extends TestCase {
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), null, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
makeUserDetails(), null);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
@ -113,25 +111,17 @@ public class CasAuthenticationTokenTests extends TestCase {
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
null, new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), new Vector(), null);
null, assertion);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), null, new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
@ -139,38 +129,31 @@ public class CasAuthenticationTokenTests extends TestCase {
}
public void testEqualsWhenEqual() {
List proxyList1 = new Vector();
proxyList1.add("https://localhost/newPortal/j_spring_cas_security_check");
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), proxyList1, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
List proxyList2 = new Vector();
proxyList2.add("https://localhost/newPortal/j_spring_cas_security_check");
makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), proxyList2, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
makeUserDetails(), assertion);
assertEquals(token1, token2);
}
public void testGetters() {
// Build the proxy list returned in the ticket from CAS
List proxyList = new Vector();
proxyList.add("https://localhost/newPortal/j_spring_cas_security_check");
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), proxyList, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
makeUserDetails(), assertion);
assertEquals("key".hashCode(), token.getKeyHash());
assertEquals(makeUserDetails(), token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertEquals("ROLE_ONE", token.getAuthorities()[0].getAuthority());
assertEquals("ROLE_TWO", token.getAuthorities()[1].getAuthority());
assertEquals("PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt", token.getProxyGrantingTicketIou());
assertEquals(proxyList, token.getProxyList());
assertEquals(assertion, token.getAssertion());
assertEquals(makeUserDetails().getUsername(), token.getUserDetails().getUsername());
}
@ -186,30 +169,25 @@ public class CasAuthenticationTokenTests extends TestCase {
}
public void testNotEqualsDueToAbstractParentEqualsCheck() {
List proxyList1 = new Vector();
proxyList1.add("https://localhost/newPortal/j_spring_cas_security_check");
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), proxyList1, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
List proxyList2 = new Vector();
proxyList2.add("https://localhost/newPortal/j_spring_cas_security_check");
makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails("OTHER_NAME"), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), proxyList2, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
makeUserDetails(), assertion);
assertTrue(!token1.equals(token2));
}
public void testNotEqualsDueToDifferentAuthenticationClass() {
List proxyList1 = new Vector();
proxyList1.add("https://localhost/newPortal/j_spring_cas_security_check");
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), proxyList1, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
makeUserDetails(), assertion);
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
@ -218,75 +196,50 @@ public class CasAuthenticationTokenTests extends TestCase {
}
public void testNotEqualsDueToKey() {
List proxyList1 = new Vector();
proxyList1.add("https://localhost/newPortal/j_spring_cas_security_check");
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), proxyList1, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
List proxyList2 = new Vector();
proxyList2.add("https://localhost/newPortal/j_spring_cas_security_check");
makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("DIFFERENT_KEY", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), proxyList2, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
makeUserDetails(), assertion);
assertTrue(!token1.equals(token2));
}
public void testNotEqualsDueToProxyGrantingTicket() {
List proxyList1 = new Vector();
proxyList1.add("https://localhost/newPortal/j_spring_cas_security_check");
public void testNotEqualsDueToAssertion() {
final Assertion assertion = new AssertionImpl("test");
final Assertion assertion2 = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), proxyList1, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
List proxyList2 = new Vector();
proxyList2.add("https://localhost/newPortal/j_spring_cas_security_check");
makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), proxyList2, "PGTIOU-SOME_OTHER_VALUE");
assertTrue(!token1.equals(token2));
}
public void testNotEqualsDueToProxyList() {
List proxyList1 = new Vector();
proxyList1.add("https://localhost/newPortal/j_spring_cas_security_check");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), proxyList1, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
List proxyList2 = new Vector();
proxyList2.add("https://localhost/SOME_OTHER_PORTAL/j_spring_cas_security_check");
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), proxyList2, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
makeUserDetails(), assertion2);
assertTrue(!token1.equals(token2));
}
public void testSetAuthenticated() {
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
makeUserDetails(), assertion);
assertTrue(token.isAuthenticated());
token.setAuthenticated(false);
assertTrue(!token.isAuthenticated());
}
public void testToString() {
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
makeUserDetails(), assertion);
String result = token.toString();
assertTrue(result.lastIndexOf("Proxy List:") != -1);
assertTrue(result.lastIndexOf("Proxy-Granting Ticket IOU:") != -1);
assertTrue(result.lastIndexOf("Credentials (Service/Proxy Ticket):") != -1);
}
}

View File

@ -1,102 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas;
import junit.framework.TestCase;
import java.util.List;
import java.util.Vector;
/**
* Tests {@link TicketResponse}.
*
* @author Ben Alex
* @version $Id$
*/
public class TicketResponseTests extends TestCase {
//~ Constructors ===================================================================================================
public TicketResponseTests() {
super();
}
public TicketResponseTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(TicketResponseTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testConstructorAcceptsNullProxyGrantingTicketIOU() {
TicketResponse ticket = new TicketResponse("rod", new Vector(), null);
assertEquals("", ticket.getProxyGrantingTicketIou());
}
public void testConstructorAcceptsNullProxyList() {
TicketResponse ticket = new TicketResponse("rod", null,
"PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
assertEquals(new Vector(), ticket.getProxyList());
}
public void testConstructorRejectsNullUser() {
try {
new TicketResponse(null, new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testGetters() {
// Build the proxy list returned in the ticket from CAS
List proxyList = new Vector();
proxyList.add("https://localhost/newPortal/j_spring_cas_security_check");
TicketResponse ticket = new TicketResponse("rod", proxyList,
"PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
assertEquals("rod", ticket.getUser());
assertEquals(proxyList, ticket.getProxyList());
assertEquals("PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt", ticket.getProxyGrantingTicketIou());
}
public void testNoArgConstructorDoesntExist() {
Class clazz = TicketResponse.class;
try {
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
} catch (NoSuchMethodException expected) {
assertTrue(true);
}
}
public void testToString() {
TicketResponse ticket = new TicketResponse("rod", null,
"PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
String result = ticket.toString();
assertTrue(result.lastIndexOf("Proxy List:") != -1);
assertTrue(result.lastIndexOf("Proxy-Granting Ticket IOU:") != -1);
assertTrue(result.lastIndexOf("User:") != -1);
}
}

View File

@ -0,0 +1,35 @@
package org.springframework.security.providers.cas.cache;
import java.util.ArrayList;
import java.util.List;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.AssertionImpl;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.providers.cas.CasAuthenticationToken;
import org.springframework.security.userdetails.User;
/**
*
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 2.0
*
*/
public abstract class AbstractStatelessTicketCacheTests {
protected CasAuthenticationToken getToken() {
List<String> proxyList = new ArrayList<String>();
proxyList.add("https://localhost/newPortal/j_spring_cas_security_check");
User user = new User("rod", "password", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
final Assertion assertion = new AssertionImpl("rod");
return new CasAuthenticationToken("key", user, "ST-0-ER94xMJmn6pha35CQRoZ",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, user,
assertion);
}
}

View File

@ -19,18 +19,11 @@ import net.sf.ehcache.Ehcache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Cache;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.providers.cas.CasAuthenticationToken;
import org.springframework.security.userdetails.User;
import java.util.List;
import java.util.Vector;
import org.junit.Test;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.springframework.security.providers.cas.CasAuthenticationToken;
import static org.junit.Assert.*;
@ -40,7 +33,7 @@ import static org.junit.Assert.*;
* @author Ben Alex
* @version $Id$
*/
public class EhCacheBasedTicketCacheTests {
public class EhCacheBasedTicketCacheTests extends AbstractStatelessTicketCacheTests {
private static CacheManager cacheManager;
//~ Methods ========================================================================================================
@ -56,27 +49,17 @@ public class EhCacheBasedTicketCacheTests {
cacheManager.shutdown();
}
private CasAuthenticationToken getToken() {
List proxyList = new Vector();
proxyList.add("https://localhost/newPortal/j_spring_cas_security_check");
User user = new User("rod", "password", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
return new CasAuthenticationToken("key", user, "ST-0-ER94xMJmn6pha35CQRoZ",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, user,
proxyList, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
}
@Test
public void testCacheOperation() throws Exception {
EhCacheBasedTicketCache cache = new EhCacheBasedTicketCache();
cache.setCache(cacheManager.getCache("castickets"));
cache.afterPropertiesSet();
final CasAuthenticationToken token = getToken();
// Check it gets stored in the cache
cache.putTicketInCache(getToken());
assertEquals(getToken(), cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ"));
cache.putTicketInCache(token);
assertEquals(token, cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ"));
// Check it gets removed from the cache
cache.removeTicketFromCache(getToken());

View File

@ -14,16 +14,12 @@
*/
package org.springframework.security.providers.cas.cache;
import java.util.ArrayList;
import java.util.List;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.junit.Test;
import org.springframework.security.providers.cas.CasAuthenticationToken;
import org.springframework.security.providers.cas.StatelessTicketCache;
import org.springframework.security.userdetails.User;
import junit.framework.TestCase;
import static org.junit.Assert.*;
/**
* Test cases for the @link {@link NullStatelessTicketCache}
@ -32,31 +28,20 @@ import junit.framework.TestCase;
* @version $Id$
*
*/
public class NullStatelessTicketCacheTests extends TestCase {
public class NullStatelessTicketCacheTests extends AbstractStatelessTicketCacheTests {
private StatelessTicketCache cache = new NullStatelessTicketCache();
@Test
public void testGetter() {
assertNull(cache.getByTicketId(null));
assertNull(cache.getByTicketId("test"));
}
@Test
public void testInsertAndGet() {
final CasAuthenticationToken token = getToken();
cache.putTicketInCache(token);
assertNull(cache.getByTicketId((String) token.getCredentials()));
}
private CasAuthenticationToken getToken() {
List<String> proxyList = new ArrayList<String>();
proxyList.add("https://localhost/newPortal/j_spring_cas_security_check");
User user = new User("rod", "password", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
return new CasAuthenticationToken("key", user, "ST-0-ER94xMJmn6pha35CQRoZ",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, user,
proxyList, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
}
}

View File

@ -1,66 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas.proxy;
import junit.framework.TestCase;
import java.util.Vector;
/**
* Tests {@link AcceptAnyCasProxy}.
*
* @author Ben Alex
* @version $Id$
*/
public class AcceptAnyCasProxyTests extends TestCase {
//~ Constructors ===================================================================================================
public AcceptAnyCasProxyTests() {
super();
}
public AcceptAnyCasProxyTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AcceptAnyCasProxyTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testDoesNotAcceptNull() {
AcceptAnyCasProxy proxyDecider = new AcceptAnyCasProxy();
try {
proxyDecider.confirmProxyListTrusted(null);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("proxyList cannot be null", expected.getMessage());
}
}
public void testNormalOperation() {
AcceptAnyCasProxy proxyDecider = new AcceptAnyCasProxy();
proxyDecider.confirmProxyListTrusted(new Vector());
assertTrue(true); // as no Exception thrown
}
}

View File

@ -1,134 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas.proxy;
import junit.framework.TestCase;
import org.springframework.security.providers.cas.ProxyUntrustedException;
import java.util.List;
import java.util.Vector;
/**
* Tests {@link NamedCasProxyDecider}.
*/
public class NamedCasProxyDeciderTests extends TestCase {
//~ Constructors ===================================================================================================
public NamedCasProxyDeciderTests() {
super();
}
public NamedCasProxyDeciderTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(NamedCasProxyDeciderTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAcceptsIfNearestProxyIsAuthorized()
throws Exception {
NamedCasProxyDecider proxyDecider = new NamedCasProxyDecider();
// Build the ticket returned from CAS
List proxyList = new Vector();
proxyList.add("https://localhost/newPortal/j_spring_cas_security_check");
// Build the list of valid nearest proxies
List validProxies = new Vector();
validProxies.add("https://localhost/portal/j_spring_cas_security_check");
validProxies.add("https://localhost/newPortal/j_spring_cas_security_check");
proxyDecider.setValidProxies(validProxies);
proxyDecider.afterPropertiesSet();
proxyDecider.confirmProxyListTrusted(proxyList);
assertTrue(true);
}
public void testAcceptsIfNoProxiesInTicket() {
NamedCasProxyDecider proxyDecider = new NamedCasProxyDecider();
List proxyList = new Vector(); // no proxies in list
proxyDecider.confirmProxyListTrusted(proxyList);
assertTrue(true);
}
public void testDetectsMissingValidProxiesList() throws Exception {
NamedCasProxyDecider proxyDecider = new NamedCasProxyDecider();
try {
proxyDecider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("A validProxies list must be set", expected.getMessage());
}
}
public void testDoesNotAcceptNull() {
NamedCasProxyDecider proxyDecider = new NamedCasProxyDecider();
try {
proxyDecider.confirmProxyListTrusted(null);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("proxyList cannot be null", expected.getMessage());
}
}
public void testGettersSetters() {
NamedCasProxyDecider proxyDecider = new NamedCasProxyDecider();
// Build the list of valid nearest proxies
List validProxies = new Vector();
validProxies.add("https://localhost/portal/j_spring_cas_security_check");
validProxies.add("https://localhost/newPortal/j_spring_cas_security_check");
proxyDecider.setValidProxies(validProxies);
assertEquals(validProxies, proxyDecider.getValidProxies());
}
public void testRejectsIfNearestProxyIsNotAuthorized()
throws Exception {
NamedCasProxyDecider proxyDecider = new NamedCasProxyDecider();
// Build the ticket returned from CAS
List proxyList = new Vector();
proxyList.add("https://localhost/untrustedWebApp/j_spring_cas_security_check");
// Build the list of valid nearest proxies
List validProxies = new Vector();
validProxies.add("https://localhost/portal/j_spring_cas_security_check");
validProxies.add("https://localhost/newPortal/j_spring_cas_security_check");
proxyDecider.setValidProxies(validProxies);
proxyDecider.afterPropertiesSet();
try {
proxyDecider.confirmProxyListTrusted(proxyList);
fail("Should have thrown ProxyUntrustedException");
} catch (ProxyUntrustedException expected) {
assertTrue(true);
}
}
}

View File

@ -1,84 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas.proxy;
import junit.framework.TestCase;
import org.springframework.security.providers.cas.ProxyUntrustedException;
import java.util.List;
import java.util.Vector;
/**
* Tests {@link RejectProxyTickets}.
*
* @author Ben Alex
* @version $Id$
*/
public class RejectProxyTicketsTests extends TestCase {
//~ Constructors ===================================================================================================
public RejectProxyTicketsTests() {
super();
}
public RejectProxyTicketsTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(RejectProxyTicketsTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAcceptsIfNoProxiesInTicket() {
RejectProxyTickets proxyDecider = new RejectProxyTickets();
List proxyList = new Vector(); // no proxies in list
proxyDecider.confirmProxyListTrusted(proxyList);
assertTrue(true);
}
public void testDoesNotAcceptNull() {
RejectProxyTickets proxyDecider = new RejectProxyTickets();
try {
proxyDecider.confirmProxyListTrusted(null);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("proxyList cannot be null", expected.getMessage());
}
}
public void testRejectsIfAnyProxyInList() {
RejectProxyTickets proxyDecider = new RejectProxyTickets();
List proxyList = new Vector();
proxyList.add("https://localhost/webApp/j_spring_cas_security_check");
try {
proxyDecider.confirmProxyListTrusted(proxyList);
fail("Should have thrown ProxyUntrustedException");
} catch (ProxyUntrustedException expected) {
assertTrue(true);
}
}
}

View File

@ -1,147 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas.ticketvalidator;
import junit.framework.TestCase;
import org.springframework.security.AuthenticationException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.providers.cas.TicketResponse;
import org.springframework.security.ui.cas.ServiceProperties;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;
import java.util.Vector;
/**
* Tests {@link AbstractTicketValidator}.
*
* @author Ben Alex
* @version $Id$
*/
public class AbstractTicketValidatorTests extends TestCase {
//~ Constructors ===================================================================================================
public AbstractTicketValidatorTests() {
}
public AbstractTicketValidatorTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public void testDetectsMissingCasValidate() throws Exception {
AbstractTicketValidator tv = new MockAbstractTicketValidator();
tv.setServiceProperties(new ServiceProperties());
try {
tv.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("A casValidate URL must be set", expected.getMessage());
}
}
public void testDetectsMissingServiceProperties() throws Exception {
AbstractTicketValidator tv = new MockAbstractTicketValidator();
tv.setCasValidate("https://company.com/cas/proxyvalidate");
try {
tv.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("serviceProperties must be specified", expected.getMessage());
}
}
public void testGetters() throws Exception {
AbstractTicketValidator tv = new MockAbstractTicketValidator();
tv.setCasValidate("https://company.com/cas/proxyvalidate");
assertEquals("https://company.com/cas/proxyvalidate", tv.getCasValidate());
tv.setServiceProperties(new ServiceProperties());
assertTrue(tv.getServiceProperties() != null);
tv.afterPropertiesSet();
tv.setTrustStore("/some/file/cacerts");
assertEquals("/some/file/cacerts", tv.getTrustStore());
}
public void testTrustStoreSystemPropertySetDuringAfterPropertiesSet() throws Exception {
AbstractTicketValidator tv = new MockAbstractTicketValidator();
tv.setCasValidate("https://company.com/cas/proxyvalidate");
tv.setServiceProperties(new ServiceProperties());
// We need an existing file to use as the truststore property
Resource r = new ClassPathResource("log4j.properties");
String filename = r.getFile().getAbsolutePath();
tv.setTrustStore(filename);
assertEquals(filename, tv.getTrustStore());
String before = System.getProperty("javax.net.ssl.trustStore");
tv.afterPropertiesSet();
assertEquals(filename, System.getProperty("javax.net.ssl.trustStore"));
if (before == null) {
System.setProperty("javax.net.ssl.trustStore", "");
} else {
System.setProperty("javax.net.ssl.trustStore", before);
}
}
public void testMissingTrustStoreFileCausesException() throws Exception {
AbstractTicketValidator tv = new MockAbstractTicketValidator();
tv.setServiceProperties(new ServiceProperties());
tv.setCasValidate("https://company.com/cas/proxyvalidate");
tv.setTrustStore("/non/existent/file");
try {
tv.afterPropertiesSet();
fail("Expected exception with non-existent truststore");
} catch (IllegalArgumentException expected) {
}
}
//~ Inner Classes ==================================================================================================
private class MockAbstractTicketValidator extends AbstractTicketValidator {
private boolean returnTicket;
public MockAbstractTicketValidator(boolean returnTicket) {
this.returnTicket = returnTicket;
}
private MockAbstractTicketValidator() {
}
public TicketResponse confirmTicketValid(String serviceTicket)
throws AuthenticationException {
if (returnTicket) {
return new TicketResponse("user", new Vector(),
"PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
}
throw new BadCredentialsException("As requested by mock");
}
}
}

View File

@ -1,136 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.cas.ticketvalidator;
import edu.yale.its.tp.cas.client.ProxyTicketValidator;
import junit.framework.TestCase;
import org.springframework.security.AuthenticationServiceException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.providers.cas.TicketResponse;
import org.springframework.security.ui.cas.ServiceProperties;
import java.util.Vector;
/**
* Tests {@link CasProxyTicketValidator}.
*
* @author Ben Alex
* @version $Id$
*/
public class CasProxyTicketValidatorTests extends TestCase {
//~ Constructors ===================================================================================================
public CasProxyTicketValidatorTests() {
super();
}
public CasProxyTicketValidatorTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(CasProxyTicketValidatorTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testGetters() {
CasProxyTicketValidator tv = new CasProxyTicketValidator();
tv.setProxyCallbackUrl("http://my.com/webapp/casProxy/someValidator");
assertEquals("http://my.com/webapp/casProxy/someValidator", tv.getProxyCallbackUrl());
}
public void testNormalOperation() {
ServiceProperties sp = new ServiceProperties();
sp.setSendRenew(true);
sp.setService("https://my.com/webapp//j_spring_cas_security_check");
CasProxyTicketValidator tv = new MockCasProxyTicketValidator(true, false);
tv.setCasValidate("https://company.com/cas/proxyvalidate");
tv.setServiceProperties(sp);
tv.setProxyCallbackUrl("http://my.com/webapp/casProxy/someValidator");
TicketResponse response = tv.confirmTicketValid("ST-0-ER94xMJmn6pha35CQRoZ");
assertEquals("user", response.getUser());
}
public void testProxyTicketValidatorInternalExceptionsGracefullyHandled() {
CasProxyTicketValidator tv = new MockCasProxyTicketValidator(false, true);
tv.setCasValidate("https://company.com/cas/proxyvalidate");
tv.setServiceProperties(new ServiceProperties());
tv.setProxyCallbackUrl("http://my.com/webapp/casProxy/someValidator");
try {
tv.confirmTicketValid("ST-0-ER94xMJmn6pha35CQRoZ");
fail("Should have thrown AuthenticationServiceException");
} catch (AuthenticationServiceException expected) {
assertTrue(true);
}
}
public void testValidationFailsOkAndOperationWithoutAProxyCallbackUrl() {
CasProxyTicketValidator tv = new MockCasProxyTicketValidator(false, false);
tv.setCasValidate("https://company.com/cas/proxyvalidate");
tv.setServiceProperties(new ServiceProperties());
try {
tv.confirmTicketValid("ST-0-ER94xMJmn6pha35CQRoZ");
fail("Should have thrown BadCredentialsExpected");
} catch (BadCredentialsException expected) {
assertTrue(true);
}
}
//~ Inner Classes ==================================================================================================
private class MockCasProxyTicketValidator extends CasProxyTicketValidator {
private boolean returnTicket;
private boolean throwAuthenticationServiceException;
public MockCasProxyTicketValidator(boolean returnTicket, boolean throwAuthenticationServiceException) {
this.returnTicket = returnTicket;
this.throwAuthenticationServiceException = throwAuthenticationServiceException;
}
private MockCasProxyTicketValidator() {
super();
}
protected TicketResponse validateNow(ProxyTicketValidator pv)
throws AuthenticationServiceException, BadCredentialsException {
if (returnTicket) {
return new TicketResponse("user", new Vector(),
"PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
}
if (throwAuthenticationServiceException) {
throw new AuthenticationServiceException("As requested by mock");
}
throw new BadCredentialsException("As requested by mock");
}
}
}

View File

@ -52,7 +52,7 @@ public class ServicePropertiesTests extends TestCase {
sp.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("service must be specified", expected.getMessage());
assertEquals("service must be specified.", expected.getMessage());
}
}

View File

@ -25,17 +25,5 @@
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
</dependency>
<dependency>
<groupId>cas</groupId>
<artifactId>casclient</artifactId>
<version>2.0.11</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>1.3.0</version>
<optional>true</optional>
</dependency>
</dependencies>
</project>