SEC-1009: Deleted container adapters

This commit is contained in:
Luke Taylor 2008-10-14 23:49:51 +00:00
parent 6364238aa2
commit 6183b7ec28
30 changed files with 0 additions and 2907 deletions

View File

@ -1 +0,0 @@
target

View File

@ -1,5 +0,0 @@
target
.settings
.classpath
.project
.wtpmodules

View File

@ -1,22 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-adapters</artifactId>
<version>2.5.0-SNAPSHOT</version>
</parent>
<artifactId>spring-security-catalina</artifactId>
<name>Spring Security - Catalina adapter</name>
<dependencies>
<dependency>
<groupId>tomcat</groupId>
<artifactId>catalina</artifactId>
<version>4.1.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,236 +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.adapters.catalina;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.apache.catalina.Container;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.realm.RealmBase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import java.io.File;
import java.security.Principal;
import java.security.cert.X509Certificate;
import java.util.Map;
/**
* Adapter to enable Catalina (Tomcat) to authenticate via the Spring Security.<p>Returns a {@link
* PrincipalSpringSecurityUserToken} to Catalina's authentication system, which is subsequently available via
* <code>HttpServletRequest.getUserPrincipal()</code>.</p>
*
* @author Ben Alex
* @version $Id:CatalinaSpringSecurityUserRealm.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class CatalinaSpringSecurityUserRealm extends RealmBase {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(CatalinaSpringSecurityUserRealm.class);
//~ Instance fields ================================================================================================
private AuthenticationManager authenticationManager;
private Container container;
private String appContextLocation;
private String key;
protected final String name = "CatalinaSpringUserRealm / $Id:CatalinaSpringSecurityUserRealm.java 2151 2007-09-22 11:54:13Z luke_t $";
//~ Methods ========================================================================================================
public Principal authenticate(String username, String credentials) {
if (username == null) {
return null;
}
if (credentials == null) {
credentials = "";
}
Authentication request = new UsernamePasswordAuthenticationToken(username, credentials);
Authentication response = null;
try {
response = authenticationManager.authenticate(request);
} catch (AuthenticationException failed) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for user: " + username + " failed: " + failed.toString());
}
return null;
}
return new PrincipalSpringSecurityUserToken(this.key, response.getPrincipal().toString(),
response.getCredentials().toString(), response.getAuthorities(), response.getPrincipal());
}
public Principal authenticate(String username, byte[] credentials) {
return authenticate(username, new String(credentials));
}
/**
* Not supported, returns null
*
* @param username DOCUMENT ME!
* @param digest DOCUMENT ME!
* @param nonce DOCUMENT ME!
* @param nc DOCUMENT ME!
* @param cnonce DOCUMENT ME!
* @param qop DOCUMENT ME!
* @param realm DOCUMENT ME!
* @param md5a2 DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public java.security.Principal authenticate(java.lang.String username, java.lang.String digest,
java.lang.String nonce, java.lang.String nc, java.lang.String cnonce, java.lang.String qop,
java.lang.String realm, java.lang.String md5a2) {
return null;
}
/**
* Not supported, returns null
*
* @param x509Certificates DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Principal authenticate(X509Certificate[] x509Certificates) {
return null;
}
public String getAppContextLocation() {
return appContextLocation;
}
public String getKey() {
return key;
}
protected String getName() {
return this.name;
}
/**
* Always returns null (we override authenticate methods)
*
* @param arg0 DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
protected String getPassword(String arg0) {
return null;
}
/**
* Always returns null (we override authenticate methods)
*
* @param arg0 DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
protected Principal getPrincipal(String arg0) {
return null;
}
public boolean hasRole(Principal principal, String role) {
if ((principal == null) || (role == null)) {
return false;
}
if (!(principal instanceof PrincipalSpringSecurityUserToken)) {
logger.warn("Expected passed principal to be of type PrincipalSpringSecurityUserToken but was "
+ principal.getClass().getName());
return false;
}
PrincipalSpringSecurityUserToken test = (PrincipalSpringSecurityUserToken) principal;
return test.isUserInRole(role);
}
public void setAppContextLocation(String appContextLocation) {
this.appContextLocation = appContextLocation;
}
public void setKey(String key) {
this.key = key;
}
/**
* Provides the method that Catalina will use to start the container.
*
* @throws LifecycleException if a problem is detected
*/
public void start() throws LifecycleException {
this.start(true);
}
private void start(boolean startParent) throws LifecycleException {
if (startParent) {
super.start();
}
if ((appContextLocation == null) || "".equals(appContextLocation)) {
throw new LifecycleException("appContextLocation must be defined");
}
if ((key == null) || "".equals(key)) {
throw new LifecycleException("key must be defined");
}
File xml = new File(System.getProperty("catalina.base"), appContextLocation);
if (!xml.exists()) {
throw new LifecycleException("appContextLocation does not seem to exist in " + xml.toString());
}
FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("file:" + xml.getAbsolutePath());
Map beans = ctx.getBeansOfType(AuthenticationManager.class, true, true);
if (beans.size() == 0) {
throw new IllegalArgumentException(
"Bean context must contain at least one bean of type AuthenticationManager");
}
String beanName = (String) beans.keySet().iterator().next();
authenticationManager = (AuthenticationManager) beans.get(beanName);
logger.info("CatalinaSpringSecurityUserRealm Started");
}
/**
* Provides a method to load the container adapter without delegating to the superclass, which cannot
* operate outside the Catalina container.
*
* @throws LifecycleException if a problem is detected
*/
protected void startForTest() throws LifecycleException {
this.start(false);
}
}

View File

@ -1,7 +0,0 @@
<html>
<body>
Adapter to Catalina web container (Tomcat).
<p>
</body>
</html>

View File

@ -1,38 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<!--
* Copyright 2004 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.
*
*
* $Id$
-->
<beans>
<!-- Data access object which stores authentication information -->
<bean id="inMemoryDaoImpl" class="org.springframework.security.userdetails.memory.InMemoryDaoImpl">
<property name="userMap">
<value>
rod=koala,ROLE_TELLER,ROLE_SUPERVISOR
dianne=emu,ROLE_TELLER
scott=wombat,ROLE_TELLER
peter=opal,disabled,ROLE_TELLER
</value>
</property>
</bean>
<!-- The authentication manager is deliberately missing in order to test error detection -->
</beans>

View File

@ -1,51 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<!--
* Copyright 2004 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.
*
*
* $Id$
-->
<beans>
<!-- Data access object which stores authentication information -->
<bean id="inMemoryDaoImpl" class="org.springframework.security.userdetails.memory.InMemoryDaoImpl">
<property name="userMap">
<value>
rod=koala,ROLE_TELLER,ROLE_SUPERVISOR
dianne=emu,ROLE_TELLER
scott=wombat,ROLE_TELLER
peter=opal,disabled,ROLE_TELLER
</value>
</property>
</bean>
<!-- Authentication provider that queries our data access object -->
<bean id="daoAuthenticationProvider" class="org.springframework.security.providers.dao.DaoAuthenticationProvider">
<property name="userDetailsService"><ref bean="inMemoryDaoImpl"/></property>
<property name="forcePrincipalAsString"><value>true</value></property>
</bean>
<!-- The authentication manager that iterates through our only authentication provider -->
<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<list>
<ref bean="daoAuthenticationProvider"/>
</list>
</property>
</bean>
</beans>

View File

@ -1,275 +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.adapters.catalina;
import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import org.apache.catalina.LifecycleException;
import java.io.File;
import java.net.URL;
import java.security.Principal;
/**
* Tests {@link CatalinaSpringSecurityUserRealm}.
*
* @author Ben Alex
* @version $Id:CatalinaSpringSecurityUserRealmTests.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class CatalinaSpringSecurityUserRealmTests extends TestCase {
//~ Instance fields ================================================================================================
private final String ADAPTER_KEY = "my_key";
//~ Constructors ===================================================================================================
public CatalinaSpringSecurityUserRealmTests() {
super();
}
public CatalinaSpringSecurityUserRealmTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(CatalinaSpringSecurityUserRealmTests.class);
}
private CatalinaSpringSecurityUserRealm makeAdapter(String fileName)
throws Exception {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
URL url = Thread.currentThread().getContextClassLoader().getResource("org/springframework/security/adapters/" + fileName);
if (url == null) {
throw new Exception("Could not find " + fileName + " - cannot continue");
}
File file = new File(url.getFile());
System.setProperty("catalina.base", file.getParentFile().getAbsolutePath());
System.out.println("catalina.base set to: " + System.getProperty("catalina.base"));
adapter.setAppContextLocation(fileName);
adapter.setKey(ADAPTER_KEY);
adapter.startForTest();
return adapter;
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAdapterAbortsIfAppContextDoesNotContainAnAuthenticationBean()
throws Exception {
try {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-invalid.xml");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testAdapterAbortsIfNoAppContextSpecified()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
adapter.setKey("KEY");
try {
adapter.startForTest();
fail("Should have thrown LifecycleException");
} catch (LifecycleException expected) {
assertEquals("appContextLocation must be defined", expected.getMessage());
}
adapter.setAppContextLocation("");
try {
adapter.startForTest();
fail("Should have thrown LifecycleException");
} catch (LifecycleException expected) {
assertEquals("appContextLocation must be defined", expected.getMessage());
}
}
public void testAdapterAbortsIfNoKeySpecified() throws Exception {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
adapter.setAppContextLocation("SOMETHING");
try {
adapter.startForTest();
fail("Should have thrown LifecycleException");
} catch (LifecycleException expected) {
assertEquals("key must be defined", expected.getMessage());
}
adapter.setKey("");
try {
adapter.startForTest();
fail("Should have thrown LifecycleException");
} catch (LifecycleException expected) {
assertEquals("key must be defined", expected.getMessage());
}
}
public void testAdapterAbortsWithIncorrectApplicationContextLocation()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
adapter.setAppContextLocation("SOME_INVALID_PATH");
adapter.setKey("KEY");
try {
adapter.startForTest();
fail("Should have thrown LifecycleException");
} catch (LifecycleException expected) {
assertTrue(expected.getMessage().startsWith("appContextLocation does not seem to exist in"));
}
}
public void testAdapterIdentifiesItself() throws Exception {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertTrue(adapter.getName().lastIndexOf("CatalinaSpringUserRealm") != -1);
}
public void testAdapterStartsUpSuccess() throws Exception {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-valid.xml");
assertTrue(true);
}
public void testAuthenticateManyParamsReturnsNull() {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertEquals(null, adapter.authenticate(null, null, null, null, null, null, null, null));
}
public void testAuthenticateX509ReturnsNull() {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertEquals(null, adapter.authenticate(null));
}
public void testAuthenticationFailsForIncorrectPassword()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-valid.xml");
assertEquals(null, adapter.authenticate("rod", "kangaroo"));
}
public void testAuthenticationFailsForIncorrectUserName()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-valid.xml");
assertEquals(null, adapter.authenticate("melissa", "koala"));
}
public void testAuthenticationUsingByteArrayForCredentials()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-valid.xml");
byte[] credentials = {'k', 'o', 'a', 'l', 'a'};
Principal result = adapter.authenticate("rod", credentials);
if (!(result instanceof PrincipalSpringSecurityUserToken)) {
fail("Should have returned PrincipalSpringSecurityUserToken");
}
PrincipalSpringSecurityUserToken castResult = (PrincipalSpringSecurityUserToken) result;
assertEquals("rod", castResult.getPrincipal());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_TELLER", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_SUPERVISOR", castResult.getAuthorities()[0].getAuthority());
assertEquals(ADAPTER_KEY.hashCode(), castResult.getKeyHash());
}
public void testAuthenticationUsingStringForCredentials()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-valid.xml");
Principal result = adapter.authenticate("rod", "koala");
if (!(result instanceof PrincipalSpringSecurityUserToken)) {
fail("Should have returned PrincipalSpringSecurityUserToken");
}
PrincipalSpringSecurityUserToken castResult = (PrincipalSpringSecurityUserToken) result;
assertEquals("rod", castResult.getPrincipal());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_TELLER", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_SUPERVISOR", castResult.getAuthorities()[0].getAuthority());
assertEquals(ADAPTER_KEY.hashCode(), castResult.getKeyHash());
}
public void testAuthenticationWithNullPasswordHandledGracefully()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-valid.xml");
assertEquals(null, adapter.authenticate("rod", (String) null));
}
public void testAuthenticationWithNullUserNameHandledGracefully()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-valid.xml");
assertEquals(null, adapter.authenticate(null, "koala"));
}
public void testGetPasswordReturnsNull() {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertEquals(null, adapter.getPassword(null));
}
public void testGetPrincipalReturnsNull() {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertEquals(null, adapter.getPrincipal(null));
}
public void testGetters() {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
adapter.setKey("KEY");
assertEquals("KEY", adapter.getKey());
adapter.setAppContextLocation("SOME_LOCATION");
assertEquals("SOME_LOCATION", adapter.getAppContextLocation());
}
public void testHasRoleWithANullPrincipalFails() {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertTrue(!adapter.hasRole(null, "ROLE_ONE"));
}
public void testHasRoleWithAPrincipalTheAdapterDidNotCreateFails() {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertTrue(!adapter.hasRole(new Principal() {
public String getName() {
return "MockPrincipal";
}
}, "ROLE_ONE"));
}
public void testHasRoleWithPrincipalAcegiUserToken() {
PrincipalSpringSecurityUserToken token = new PrincipalSpringSecurityUserToken("KEY", "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
null);
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertTrue(adapter.hasRole(token, "ROLE_ONE"));
assertTrue(adapter.hasRole(token, "ROLE_TWO"));
assertTrue(!adapter.hasRole(token, "ROLE_WE_DO_NOT_HAVE"));
}
}

View File

@ -1,5 +0,0 @@
target
.settings
.classpath
.project
.wtpmodules

View File

@ -1,26 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-adapters</artifactId>
<version>2.5.0-SNAPSHOT</version>
</parent>
<artifactId>spring-security-jboss</artifactId>
<name>Spring Security - JBoss adapter</name>
<dependencies>
<dependency>
<groupId>jboss</groupId>
<artifactId>jbosssx</artifactId>
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,146 +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.adapters.jboss;
import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.context.HttpSessionContextIntegrationFilter;
import org.springframework.security.context.SecurityContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.security.Principal;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.security.auth.Subject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* Populates a {@link SecurityContext} from JBoss' <code>java:comp/env/security/subject</code>.
* <p>This filter <b>never</b> preserves the <code>Authentication</code> on the <code>ContextHolder</code> -
* it is replaced every request.</p>
* <p>See {@link HttpSessionContextIntegrationFilter} for further information.</p>
*
* @author Ben Alex
* @version $Id$
*/
public class JbossIntegrationFilter implements Filter {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(JbossIntegrationFilter.class);
//~ Methods ========================================================================================================
/**
* Does nothing. We use IoC container lifecycle services instead.
*/
public void destroy() {}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
Object principal = extractFromContainer(request);
if ((principal != null) && principal instanceof Authentication) {
SecurityContextHolder.getContext().setAuthentication((Authentication) principal);
if (logger.isDebugEnabled()) {
logger.debug("ContextHolder updated with Authentication from container: '" + principal + "'");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("ContextHolder not set with new Authentication as Principal was: '" + principal + "'");
}
}
chain.doFilter(request, response);
}
private Object extractFromContainer(ServletRequest request) {
Subject subject = null;
try {
Context lc = this.getLookupContext();
if (lc == null) {
if (logger.isWarnEnabled()) {
logger.warn("Could not obtain a Context to perform lookup");
}
return null;
}
Object result = lc.lookup("java:comp/env/security/subject");
if (result instanceof Subject) {
subject = (Subject) result;
}
} catch (NamingException ne) {
if (logger.isWarnEnabled()) {
logger.warn("Lookup on Subject failed " + ne.getLocalizedMessage());
}
}
if ((subject != null) && (subject.getPrincipals() != null)) {
Iterator principals = subject.getPrincipals().iterator();
while (principals.hasNext()) {
Principal p = (Principal) principals.next();
if (p instanceof Authentication) {
return p;
}
}
}
return null;
}
/**
* Provided so that unit tests can override.
*
* @return a <code>Context</code> that can be used for lookup
*
* @throws NamingException DOCUMENT ME!
*/
protected Context getLookupContext() throws NamingException {
return new InitialContext();
}
/**
* Does nothing. We use IoC container lifecycle services instead.
*
* @param arg0 ignored
*
* @throws ServletException ignored
*/
public void init(FilterConfig arg0) throws ServletException {}
}

View File

@ -1,302 +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.adapters.jboss;
import org.springframework.security.AccountExpiredException;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.CredentialsExpiredException;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.jboss.security.SimpleGroup;
import org.jboss.security.SimplePrincipal;
import org.jboss.security.auth.spi.AbstractServerLoginModule;
import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.beans.factory.access.SingletonBeanFactoryLocator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.security.Principal;
import java.security.acl.Group;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
/**
* Adapter to enable JBoss to authenticate via the Spring Security System for Spring.
* <p>Returns a {@link PrincipalSpringSecurityUserToken} to JBoss' authentication system,
* which is subsequently available from <code>java:comp/env/security/subject</code>.</p>
*
* @author Ben Alex
* @author Sergio Bern
* @version $Id:JbossSpringSecurityLoginModule.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class JbossSpringSecurityLoginModule extends AbstractServerLoginModule {
//~ Instance fields ================================================================================================
private AuthenticationManager authenticationManager;
private Principal identity;
private String key;
private char[] credential;
//~ Methods ========================================================================================================
protected Principal getIdentity() {
return this.identity;
}
protected Group[] getRoleSets() throws LoginException {
SimpleGroup roles = new SimpleGroup("Roles");
Group[] roleSets = {roles};
if (this.identity instanceof Authentication) {
Authentication user = (Authentication) this.identity;
for (int i = 0; i < user.getAuthorities().length; i++) {
roles.addMember(new SimplePrincipal(user.getAuthorities()[i].getAuthority()));
}
}
return roleSets;
}
protected String[] getUsernameAndPassword() throws LoginException {
String[] info = {null, null};
// prompt for a username and password
if (callbackHandler == null) {
throw new LoginException("Error: no CallbackHandler available " + "to collect authentication information");
}
NameCallback nc = new NameCallback("User name: ", "guest");
PasswordCallback pc = new PasswordCallback("Password: ", false);
Callback[] callbacks = {nc, pc};
String username = null;
String password = null;
try {
callbackHandler.handle(callbacks);
username = nc.getName();
char[] tmpPassword = pc.getPassword();
if (tmpPassword != null) {
credential = new char[tmpPassword.length];
System.arraycopy(tmpPassword, 0, credential, 0, tmpPassword.length);
pc.clearPassword();
password = new String(credential);
}
} catch (java.io.IOException ioe) {
throw new LoginException(ioe.toString());
} catch (UnsupportedCallbackException uce) {
throw new LoginException("CallbackHandler does not support: " + uce.getCallback());
}
info[0] = username;
info[1] = password;
return info;
}
public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
super.initialize(subject, callbackHandler, sharedState, options);
if (super.log.isInfoEnabled()) {
super.log.info("initializing jboss login module");
}
this.key = (String) options.get("key");
if ((key == null) || "".equals(key)) {
throw new IllegalArgumentException("key must be defined");
}
String singletonId = (String) options.get("singletonId");
String appContextLocation = (String) options.get("appContextLocation");
if ((((singletonId == null) || "".equals(singletonId)) && (appContextLocation == null))
|| "".equals(appContextLocation)) {
throw new IllegalArgumentException("appContextLocation must be defined");
}
String beanName = (String) options.get("authenticationManager");
// Attempt to find the appContextLocation only if no singletonId was defined
if ((singletonId == null) || "".equals(singletonId)) {
if (Thread.currentThread().getContextClassLoader().getResource(appContextLocation) == null) {
if (super.log.isInfoEnabled()) {
super.log.info("cannot locate " + appContextLocation);
}
throw new IllegalArgumentException("Cannot locate " + appContextLocation);
}
}
ApplicationContext ctx = null;
if ((singletonId == null) || "".equals(singletonId)) {
try {
ctx = new ClassPathXmlApplicationContext(appContextLocation);
} catch (Exception e) {
if (super.log.isInfoEnabled()) {
super.log.info("error loading spring context " + appContextLocation + " " + e);
}
throw new IllegalArgumentException("error loading spring context " + appContextLocation + " " + e);
}
} else {
if (super.log.isInfoEnabled()) {
super.log.debug("retrieving singleton instance " + singletonId);
}
BeanFactoryLocator bfl = SingletonBeanFactoryLocator.getInstance();
BeanFactoryReference bf = bfl.useBeanFactory(singletonId);
ctx = (ApplicationContext) bf.getFactory();
if (ctx == null) {
if (super.log.isInfoEnabled()) {
super.log.info("singleton " + beanName + " does not exists");
}
throw new IllegalArgumentException("singleton " + singletonId + " does not exists");
}
}
if ((beanName == null) || "".equals(beanName)) {
Map beans = null;
try {
beans = ctx.getBeansOfType(AuthenticationManager.class, true, true);
} catch (Exception e) {
if (super.log.isInfoEnabled()) {
super.log.info("exception in getBeansOfType " + e);
}
throw new IllegalStateException("spring error in get beans by class");
}
if (beans.size() == 0) {
throw new IllegalArgumentException(
"Bean context must contain at least one bean of type AuthenticationManager");
}
beanName = (String) beans.keySet().iterator().next();
}
authenticationManager = (AuthenticationManager) ctx.getBean(beanName);
if (super.log.isInfoEnabled()) {
super.log.info("Successfully started JbossSpringLoginModule");
}
}
public boolean login() throws LoginException {
super.loginOk = false;
String[] info = getUsernameAndPassword();
String username = info[0];
String password = info[1];
if ((username == null) && (password == null)) {
identity = null;
super.log.trace("Authenticating as unauthenticatedIdentity=" + identity);
}
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
if (super.log.isDebugEnabled()) {
super.log.debug("checking identity");
}
if (identity == null) {
super.log.debug("creating usernamepassword token");
Authentication request = new UsernamePasswordAuthenticationToken(username, password);
Authentication response = null;
try {
if (super.log.isDebugEnabled()) {
super.log.debug("attempting authentication");
}
response = authenticationManager.authenticate(request);
if (super.log.isDebugEnabled()) {
super.log.debug("authentication succeded");
}
} catch (CredentialsExpiredException cee) {
if (super.log.isDebugEnabled()) {
super.log.debug("Credential has expired");
}
throw new javax.security.auth.login.CredentialExpiredException(
"The credential used to identify the user has expired");
} catch (AccountExpiredException cee) {
if (super.log.isDebugEnabled()) {
super.log.debug("Account has expired, throwing jaas exception");
}
throw new javax.security.auth.login.AccountExpiredException(
"The account specified in login has expired");
} catch (AuthenticationException failed) {
if (super.log.isDebugEnabled()) {
super.log.debug("Bad password for username=" + username);
}
throw new FailedLoginException("Password Incorrect/Password Required");
}
super.log.debug("user is logged. redirecting to jaas classes");
identity = new PrincipalSpringSecurityUserToken(this.key, response.getName(), response.getCredentials().toString(),
response.getAuthorities(), response.getPrincipal());
}
if (getUseFirstPass() == true) {
// Add the username and password to the shared state map
sharedState.put("javax.security.auth.login.name", username);
sharedState.put("javax.security.auth.login.password", credential);
}
super.loginOk = true;
super.log.trace("User '" + identity + "' authenticated, loginOk=" + loginOk);
return true;
}
}

View File

@ -1,7 +0,0 @@
<html>
<body>
Adapter to JBoss.
<p>
</body>
</html>

View File

@ -1,184 +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.adapters.jboss;
import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.context.SecurityContextImpl;
import org.springframework.mock.web.MockHttpServletRequest;
import java.io.IOException;
import java.security.Principal;
import java.util.HashSet;
import java.util.Set;
import javax.naming.Context;
import javax.security.auth.Subject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* Tests {@link JbossIntegrationFilter}.
*
* @author Ben Alex
* @version $Id:JbossIntegrationFilterTests.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class JbossIntegrationFilterTests extends TestCase {
//~ Constructors ===================================================================================================
public JbossIntegrationFilterTests() {
super();
}
public JbossIntegrationFilterTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
private void executeFilterInContainerSimulator(FilterConfig filterConfig, Filter filter, ServletRequest request,
ServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
filter.init(filterConfig);
filter.doFilter(request, response, filterChain);
filter.destroy();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(JbossIntegrationFilterTests.class);
}
private Subject makeIntoSubject(Principal principal) {
Set principals = new HashSet();
principals.add(principal);
return new Subject(false, principals, new HashSet(), new HashSet());
}
protected void setUp() throws Exception {
super.setUp();
SecurityContextHolder.setContext(new SecurityContextImpl());
}
protected void tearDown() throws Exception {
super.tearDown();
SecurityContextHolder.setContext(new SecurityContextImpl());
}
public void testCorrectOperation() throws Exception {
PrincipalSpringSecurityUserToken principal = new PrincipalSpringSecurityUserToken("key", "someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_ROLE")}, null);
JbossIntegrationFilter filter = new MockJbossIntegrationFilter(new MockInitialContext(makeIntoSubject(principal)));
MockHttpServletRequest request = new MockHttpServletRequest();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertEquals(principal, SecurityContextHolder.getContext().getAuthentication());
SecurityContextHolder.setContext(new SecurityContextImpl());
}
public void testReturnsNullIfContextReturnsSomethingOtherThanASubject()
throws Exception {
JbossIntegrationFilter filter = new MockJbossIntegrationFilter(new MockInitialContext("THIS_IS_NOT_A_SUBJECT"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
public void testReturnsNullIfInitialContextHasNullPrincipal()
throws Exception {
JbossIntegrationFilter filter = new MockJbossIntegrationFilter(new MockInitialContext(makeIntoSubject(null)));
MockHttpServletRequest request = new MockHttpServletRequest();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
public void testReturnsNullIfInitialContextHasNullSubject()
throws Exception {
JbossIntegrationFilter filter = new MockJbossIntegrationFilter(new MockInitialContext(null));
MockHttpServletRequest request = new MockHttpServletRequest();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
public void testReturnsNullIfInitialContextIsNull()
throws Exception {
JbossIntegrationFilter filter = new MockJbossIntegrationFilter(null);
MockHttpServletRequest request = new MockHttpServletRequest();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
public void testReturnsNullIfPrincipalNotAnAuthenticationImplementation()
throws Exception {
JbossIntegrationFilter filter = new MockJbossIntegrationFilter(new MockInitialContext(makeIntoSubject(
new Principal() {
public String getName() {
return "MockPrincipal";
}
})));
MockHttpServletRequest request = new MockHttpServletRequest();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
public void testTestingObjectReturnsInitialContext()
throws Exception {
JbossIntegrationFilter filter = new JbossIntegrationFilter();
assertTrue(filter.getLookupContext() instanceof Context);
}
//~ Inner Classes ==================================================================================================
private class MockFilterChain implements FilterChain {
public void doFilter(ServletRequest arg0, ServletResponse arg1)
throws IOException, ServletException {}
}
}

View File

@ -1,356 +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.adapters.jboss;
import junit.framework.TestCase;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import org.jboss.security.SimplePrincipal;
import java.io.IOException;
import java.security.Principal;
import java.security.acl.Group;
import java.util.Properties;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
/**
* Tests {@link JbossSpringSecurityLoginModule}.
*
* @author Ben Alex
* @version $Id:JbossSpringSecurityLoginModuleTests.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class JbossSpringSecurityLoginModuleTests extends TestCase {
//~ Instance fields ================================================================================================
private final String ADAPTER_KEY = "my_key";
//~ Constructors ===================================================================================================
public JbossSpringSecurityLoginModuleTests() {
super();
}
public JbossSpringSecurityLoginModuleTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(JbossSpringSecurityLoginModuleTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAdapterAbortsIfAppContextDoesNotContainAnAuthenticationBean()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-invalid.xml");
try {
adapter.initialize(null, null, null, props);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testAdapterAbortsIfNoAppContextSpecified()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
try {
adapter.initialize(null, null, null, props);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("appContextLocation must be defined", expected.getMessage());
}
props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "");
try {
adapter.initialize(null, null, null, props);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("appContextLocation must be defined", expected.getMessage());
}
}
public void testAdapterAbortsIfNoKeySpecified() throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
try {
adapter.initialize(null, null, null, props);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("key must be defined", expected.getMessage());
}
props = new Properties();
props.put("key", "");
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
try {
adapter.initialize(null, null, null, props);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("key must be defined", expected.getMessage());
}
}
public void testAdapterAbortsWithIncorrectApplicationContextLocation()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "INVALID_PATH");
try {
adapter.initialize(null, null, null, props);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue("Cannot locate INVALID_PATH".equals(expected.getMessage()));
}
}
public void testAdapterFailsToAuthenticateIfNoCallbackHandlerAvailable()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
adapter.initialize(subject, null, null, props);
try {
adapter.login();
} catch (LoginException loginException) {
assertEquals("Error: no CallbackHandler available to collect authentication information",
loginException.getMessage());
}
}
public void testAdapterStartsUpSuccess() throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
adapter.initialize(null, null, null, props);
assertTrue(true);
}
public void testAuthenticationFailsForIncorrectPassword()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
CallbackHandler callback = new MockCallbackHandler("rod", "kangaroo");
adapter.initialize(subject, callback, null, props);
try {
adapter.login();
fail("Should have thrown FailedLoginException");
} catch (FailedLoginException expected) {
assertTrue(true);
}
}
public void testAuthenticationFailsForIncorrectUserName()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
CallbackHandler callback = new MockCallbackHandler("melissa", "koala");
adapter.initialize(subject, callback, null, props);
try {
adapter.login();
fail("Should have thrown FailedLoginException");
} catch (FailedLoginException expected) {
assertTrue(true);
}
}
public void testAuthenticationSuccess() throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
CallbackHandler callback = new MockCallbackHandler("rod", "koala");
adapter.initialize(subject, callback, null, props);
assertTrue(adapter.login());
Principal result = adapter.getIdentity();
if (!(result instanceof PrincipalSpringSecurityUserToken)) {
fail("Should have returned PrincipalSpringSecurityUserToken");
}
PrincipalSpringSecurityUserToken castResult = (PrincipalSpringSecurityUserToken) result;
assertEquals("rod", castResult.getPrincipal());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_TELLER", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_SUPERVISOR", castResult.getAuthorities()[0].getAuthority());
assertEquals(ADAPTER_KEY.hashCode(), castResult.getKeyHash());
}
public void testAuthenticationWithNullPasswordHandledGracefully()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
CallbackHandler callback = new MockCallbackHandler("rod", null);
adapter.initialize(subject, callback, null, props);
try {
adapter.login();
fail("Should have thrown FailedLoginException");
} catch (FailedLoginException expected) {
assertTrue(true);
}
}
public void testAuthenticationWithNullUserNameAndNullPasswordHandledGracefully()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
CallbackHandler callback = new MockCallbackHandler(null, null);
adapter.initialize(subject, callback, null, props);
try {
adapter.login();
fail("Should have thrown FailedLoginException");
} catch (FailedLoginException expected) {
assertTrue(true);
}
}
public void testAuthenticationWithNullUserNameHandledGracefully()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
CallbackHandler callback = new MockCallbackHandler(null, "kangaroo");
adapter.initialize(subject, callback, null, props);
try {
adapter.login();
fail("Should have thrown FailedLoginException");
} catch (FailedLoginException expected) {
assertTrue(true);
}
}
public void testGetRoleSets() throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
CallbackHandler callback = new MockCallbackHandler("rod", "koala");
adapter.initialize(subject, callback, null, props);
assertTrue(adapter.login());
Group[] result = adapter.getRoleSets();
// Expect Roles group.
assertEquals(1, result.length);
Group roles = result[0];
assertTrue(roles.isMember(new SimplePrincipal("ROLE_TELLER")));
assertTrue(roles.isMember(new SimplePrincipal("ROLE_SUPERVISOR")));
}
//~ Inner Classes ==================================================================================================
private class MockCallbackHandler implements CallbackHandler {
private String password;
private String username;
public MockCallbackHandler(String username, String password) {
this.username = username;
this.password = password;
}
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
((NameCallback) callbacks[i]).setName(username);
} else if (callbacks[i] instanceof PasswordCallback) {
if (this.password == null) {
((PasswordCallback) callbacks[i]).setPassword(null);
} else {
((PasswordCallback) callbacks[i]).setPassword(password.toCharArray());
}
} else {
throw new UnsupportedCallbackException(callbacks[i]);
}
}
}
}
}

View File

@ -1,167 +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.adapters.jboss;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
/**
* Mocks a <code>javax.naming.Context</code> and returns an <code>Object</code> when queried for address
* <code>java:comp/env/security/subject</code>.
*
* @author Ben Alex
* @version $Id:MockInitialContext.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class MockInitialContext implements Context {
//~ Instance fields ================================================================================================
private Object object;
//~ Constructors ===================================================================================================
public MockInitialContext(Object object) {
this.object = object;
}
//~ Methods ========================================================================================================
public Object addToEnvironment(String propName, Object propVal)
throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void bind(String name, Object obj) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void bind(Name name, Object obj) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void close() throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public String composeName(String name, String prefix)
throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Name composeName(Name name, Name prefix) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Context createSubcontext(String name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Context createSubcontext(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void destroySubcontext(String name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void destroySubcontext(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Hashtable getEnvironment() throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getNameInNamespace() throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public NameParser getNameParser(String name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public NameParser getNameParser(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public NamingEnumeration list(String name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public NamingEnumeration list(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public NamingEnumeration listBindings(String name)
throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public NamingEnumeration listBindings(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Object lookup(String name) throws NamingException {
return this.object;
}
public Object lookup(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Object lookupLink(String name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Object lookupLink(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void rebind(String name, Object obj) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void rebind(Name name, Object obj) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Object removeFromEnvironment(String propName)
throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void rename(String oldName, String newName)
throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void rename(Name oldName, Name newName) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void unbind(String name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void unbind(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
}

View File

@ -1,45 +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.adapters.jboss;
import javax.naming.Context;
import javax.naming.NamingException;
/**
* Provides mock of <code>JbossIntegrationFilter</code>, using a lookup <code>Context</code> provided in the
* constructor.
*
* @author Ben Alex
* @version $Id:MockJbossIntegrationFilter.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class MockJbossIntegrationFilter extends JbossIntegrationFilter {
//~ Instance fields ================================================================================================
private Context context;
//~ Constructors ===================================================================================================
public MockJbossIntegrationFilter(Context context) {
this.context = context;
}
//~ Methods ========================================================================================================
protected Context getLookupContext() throws NamingException {
return this.context;
}
}

View File

@ -1,5 +0,0 @@
target
.settings
.classpath
.project
.wtpmodules

View File

@ -1,22 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-adapters</artifactId>
<version>2.5.0-SNAPSHOT</version>
</parent>
<artifactId>spring-security-jetty</artifactId>
<name>Spring Security - Jetty adapter</name>
<dependencies>
<dependency>
<groupId>jetty</groupId>
<artifactId>org.mortbay.jetty</artifactId>
<version>4.2.22</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,161 +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.adapters.jetty;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
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.mortbay.http.HttpRequest;
import org.mortbay.http.UserPrincipal;
import org.mortbay.http.UserRealm;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Map;
/**
* Adapter to enable Jetty to authenticate via Spring Security.<p>Returns a {@link
* JettySpringSecurityUserToken} to Jetty's authentication system, which is subsequently available via
* <code>HttpServletRequest.getUserPrincipal()</code>.</p>
*
* @author Ben Alex
* @version $Id:JettySpringSecurityUserRealm.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public final class JettySpringSecurityUserRealm implements UserRealm {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(JettySpringSecurityUserRealm.class);
//~ Instance fields ================================================================================================
private AuthenticationManager authenticationManager;
private String key;
private String realm;
//~ Constructors ===================================================================================================
/**
* Construct a <code>SpringUserRealm</code>.
*
* @param realm the name of the authentication realm (within Jetty)
* @param providerKey a password to sign all authentication objects
* @param appContextLocation the classpath location of the bean context XML
* file
*
* @throws IllegalArgumentException DOCUMENT ME!
*/
public JettySpringSecurityUserRealm(String realm, String providerKey, String appContextLocation) {
this.realm = realm;
this.key = providerKey;
if ((realm == null) || "".equals(realm)) {
throw new IllegalArgumentException("realm must be specified");
}
if ((key == null) || "".equals(key)) {
throw new IllegalArgumentException("key must be specified");
}
if ((appContextLocation == null) || "".equals(appContextLocation)) {
throw new IllegalArgumentException("appContextLocation must be specified");
}
if (Thread.currentThread().getContextClassLoader().getResource(appContextLocation) == null) {
throw new IllegalArgumentException("Cannot locate " + appContextLocation);
}
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(appContextLocation);
Map beans = ctx.getBeansOfType(AuthenticationManager.class, true, true);
if (beans.size() == 0) {
throw new IllegalArgumentException(
"Bean context must contain at least one bean of type AuthenticationManager");
}
String beanName = (String) beans.keySet().iterator().next();
authenticationManager = (AuthenticationManager) beans.get(beanName);
}
protected JettySpringSecurityUserRealm() {
throw new IllegalArgumentException("Cannot use default constructor");
}
//~ Methods ========================================================================================================
public UserPrincipal authenticate(String username, Object password, HttpRequest httpRequest) {
if (username == null) {
return null;
}
if (password == null) {
password = "";
}
Authentication request = new UsernamePasswordAuthenticationToken(username.toString(), password.toString());
Authentication response = null;
try {
response = authenticationManager.authenticate(request);
} catch (AuthenticationException failed) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for user: " + username + " failed: " + failed.toString());
}
return null;
}
return new JettySpringSecurityUserToken(this.key, response.getPrincipal().toString(),
response.getCredentials().toString(), response.getAuthorities());
}
public void disassociate(UserPrincipal userPrincipal) {
// No action required
}
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
/**
* Accesses the realm name.
*
* @return the name of the realm as defined when <code>SpringUserRealm</code> was created
*/
public String getName() {
return this.realm;
}
public void logout(UserPrincipal arg0) {
// Not supported
}
public UserPrincipal popRole(UserPrincipal userPrincipal) {
// Not supported
return userPrincipal;
}
public UserPrincipal pushRole(UserPrincipal userPrincipal, String role) {
// Not supported
return userPrincipal;
}
}

View File

@ -1,63 +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.adapters.jetty;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.adapters.AbstractAdapterAuthenticationToken;
import org.mortbay.http.UserPrincipal;
/**
* A Jetty compatible {@link org.springframework.security.Authentication} object.
*
* @author Ben Alex
* @version $Id:JettySpringSecurityUserToken.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class JettySpringSecurityUserToken extends AbstractAdapterAuthenticationToken implements UserPrincipal {
//~ Instance fields ================================================================================================
private static final long serialVersionUID = 1L;
private String password;
private String username;
//~ Constructors ===================================================================================================
public JettySpringSecurityUserToken(String key, String username, String password, GrantedAuthority[] authorities) {
super(key, authorities);
this.username = username;
this.password = password;
}
protected JettySpringSecurityUserToken() {
throw new IllegalArgumentException("Cannot use default constructor");
}
//~ Methods ========================================================================================================
public Object getCredentials() {
return this.password;
}
public String getName() {
return this.username;
}
public Object getPrincipal() {
return this.username;
}
}

View File

@ -1,7 +0,0 @@
<html>
<body>
Adapter to Jetty web container.
<p>
</body>
</html>

View File

@ -1,237 +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.adapters.jetty;
import junit.framework.TestCase;
import org.mortbay.http.UserPrincipal;
/**
* Tests {@link JettySpringSecurityUserRealm}.
*
* @author Ben Alex
* @version $Id:JettyAcegiUserRealmTests.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class JettyAcegiUserRealmTests extends TestCase {
//~ Instance fields ================================================================================================
private final String ADAPTER_KEY = "my_key";
private final String REALM_NAME = "Acegi Powered Realm";
//~ Constructors ===================================================================================================
public JettyAcegiUserRealmTests() {
super();
}
public JettyAcegiUserRealmTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(JettyAcegiUserRealmTests.class);
}
private JettySpringSecurityUserRealm makeAdapter(String fileName)
throws Exception {
String useFile = "org/springframework/security/adapters/" + fileName;
return new JettySpringSecurityUserRealm(REALM_NAME, ADAPTER_KEY, useFile);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAdapterAbortsIfAppContextDoesNotContainAnAuthenticationBean()
throws Exception {
try {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-invalid.xml");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("Bean context must contain at least one bean of type AuthenticationManager",
expected.getMessage());
}
}
public void testAdapterAbortsIfNoAppContextSpecified()
throws Exception {
try {
new JettySpringSecurityUserRealm(REALM_NAME, ADAPTER_KEY, null);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("appContextLocation must be specified", expected.getMessage());
}
try {
new JettySpringSecurityUserRealm(REALM_NAME, ADAPTER_KEY, "");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("appContextLocation must be specified", expected.getMessage());
}
}
public void testAdapterAbortsIfNoKeySpecified() throws Exception {
try {
new JettySpringSecurityUserRealm(REALM_NAME, null, "SOME_PATH");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("key must be specified", expected.getMessage());
}
try {
new JettySpringSecurityUserRealm(REALM_NAME, "", "SOME_PATH");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("key must be specified", expected.getMessage());
}
}
public void testAdapterAbortsIfNoRealmNameSpecified()
throws Exception {
try {
new JettySpringSecurityUserRealm(null, ADAPTER_KEY, "SOME_PATH");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("realm must be specified", expected.getMessage());
}
try {
new JettySpringSecurityUserRealm(null, ADAPTER_KEY, "SOME_PATH");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("realm must be specified", expected.getMessage());
}
}
public void testAdapterAbortsWithIncorrectApplicationContextLocation()
throws Exception {
try {
new JettySpringSecurityUserRealm(REALM_NAME, ADAPTER_KEY, "SOME_INVALID_LOCATION");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(expected.getMessage().startsWith("Cannot locate"));
}
}
public void testAdapterIdentifiesTheRealmItManages()
throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
assertEquals(REALM_NAME, adapter.getName());
}
public void testAdapterStartsUpSuccess() throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
assertTrue(true);
}
public void testAuthenticationFailsForIncorrectPassword()
throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
assertEquals(null, adapter.authenticate("rod", "kangaroo", null));
}
public void testAuthenticationFailsForIncorrectUserName()
throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
assertEquals(null, adapter.authenticate("melissa", "koala", null));
}
public void testAuthenticationSuccess() throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
UserPrincipal result = adapter.authenticate("rod", "koala", null);
if (!(result instanceof JettySpringSecurityUserToken)) {
fail("Should have returned JettySpringSecurityUserToken");
}
JettySpringSecurityUserToken castResult = (JettySpringSecurityUserToken) result;
assertEquals("rod", castResult.getPrincipal());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_TELLER", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_SUPERVISOR", castResult.getAuthorities()[0].getAuthority());
assertEquals(ADAPTER_KEY.hashCode(), castResult.getKeyHash());
}
public void testAuthenticationWithNullPasswordHandledGracefully()
throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
assertEquals(null, adapter.authenticate("rod", null, null));
}
public void testAuthenticationWithNullUserNameHandledGracefully()
throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
assertEquals(null, adapter.authenticate(null, "koala", null));
}
public void testDisassociateImplemented() throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
adapter.disassociate(new MockUserPrincipal());
assertTrue(true);
}
public void testGetAuthenticationManager() throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
assertTrue(adapter.getAuthenticationManager() != null);
}
public void testLogoutImplemented() throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
adapter.logout(new MockUserPrincipal());
assertTrue(true);
}
public void testNoArgsConstructor() {
try {
new JettySpringSecurityUserRealm();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testPopRoleImplemented() throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
MockUserPrincipal user = new MockUserPrincipal();
assertEquals(user, adapter.popRole(user));
}
public void testPushRoleImplemented() throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
MockUserPrincipal user = new MockUserPrincipal();
assertEquals(user, adapter.pushRole(user, "SOME_ROLE"));
}
//~ Inner Classes ==================================================================================================
private class MockUserPrincipal implements UserPrincipal {
public String getName() {
throw new UnsupportedOperationException("mock method not implemented");
}
public boolean isAuthenticated() {
throw new UnsupportedOperationException("mock method not implemented");
}
public boolean isUserInRole(String arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
}
}

View File

@ -1,59 +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.adapters.jetty;
import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
/**
* Tests {@link JettySpringSecurityUserToken}.
*
* @author Ben Alex
* @version $Id:JettySpringSecurityUserTokenTests.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class JettySpringSecurityUserTokenTests extends TestCase {
//~ Constructors ===================================================================================================
public JettySpringSecurityUserTokenTests() {
}
public JettySpringSecurityUserTokenTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public void testGetters() throws Exception {
JettySpringSecurityUserToken token = new JettySpringSecurityUserToken("my_password", "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertEquals("Test", token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertEquals("my_password".hashCode(), token.getKeyHash());
assertEquals("Test", token.getName());
}
public void testNoArgsConstructor() {
try {
new JettySpringSecurityUserToken();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
}

View File

@ -1,29 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-parent</artifactId>
<version>2.5.0-SNAPSHOT</version>
</parent>
<artifactId>spring-security-adapters</artifactId>
<name>Spring Security - Adapters</name>
<packaging>pom</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<modules>
<module>catalina</module>
<module>jboss</module>
<module>jetty</module>
<module>resin</module>
</modules>
</project>

View File

@ -1,5 +0,0 @@
target
.settings
.classpath
.project
.wtpmodules

View File

@ -1,26 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-adapters</artifactId>
<version>2.5.0-SNAPSHOT</version>
</parent>
<artifactId>spring-security-resin</artifactId>
<name>Spring Security - Resin adapter</name>
<dependencies>
<dependency>
<groupId>com.caucho</groupId>
<artifactId>resin</artifactId>
<version>3.0.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,152 +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.adapters.resin;
import com.caucho.http.security.AbstractAuthenticator;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.security.Principal;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Adapter to enable Resin to authenticate via Spring Security.<p>Returns a {@link
* PrincipalSpringSecurityUserToken} to Resin's authentication system, which is subsequently available via
* <code>HttpServletRequest.getUserPrincipal()</code>.</p>
*
* @author Ben Alex
* @version $Id:ResinAcegiAuthenticator.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class ResinAcegiAuthenticator extends AbstractAuthenticator {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(ResinAcegiAuthenticator.class);
//~ Instance fields ================================================================================================
private AuthenticationManager authenticationManager;
private String appContextLocation;
private String key;
//~ Methods ========================================================================================================
public String getAppContextLocation() {
return appContextLocation;
}
public String getKey() {
return key;
}
public void init() throws ServletException {
super.init();
if ((appContextLocation == null) || "".equals(appContextLocation)) {
throw new ServletException("appContextLocation must be defined");
}
if ((key == null) || "".equals(key)) {
throw new ServletException("key must be defined");
}
if (Thread.currentThread().getContextClassLoader().getResource(appContextLocation) == null) {
throw new ServletException("Cannot locate " + appContextLocation);
}
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(appContextLocation);
Map beans = ctx.getBeansOfType(AuthenticationManager.class, true, true);
if (beans.size() == 0) {
throw new ServletException("Bean context must contain at least one bean of type AuthenticationManager");
}
String beanName = (String) beans.keySet().iterator().next();
authenticationManager = (AuthenticationManager) beans.get(beanName);
logger.info("ResinAcegiAuthenticator Started");
}
public boolean isUserInRole(HttpServletRequest request, HttpServletResponse response, ServletContext application,
Principal principal, String role) {
if (!(principal instanceof PrincipalSpringSecurityUserToken)) {
if (logger.isWarnEnabled()) {
logger.warn("Expected passed principal to be of type PrincipalSpringSecurityUserToken");
}
return false;
}
PrincipalSpringSecurityUserToken test = (PrincipalSpringSecurityUserToken) principal;
return test.isUserInRole(role);
}
protected Principal loginImpl(String username, String credentials) {
if (username == null) {
return null;
}
if (credentials == null) {
credentials = "";
}
Authentication request = new UsernamePasswordAuthenticationToken(username, credentials);
Authentication response = null;
try {
response = authenticationManager.authenticate(request);
} catch (AuthenticationException failed) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for user: " + username + " failed: " + failed.toString());
}
return null;
}
return new PrincipalSpringSecurityUserToken(this.key, response.getPrincipal().toString(),
response.getCredentials().toString(), response.getAuthorities(), response.getPrincipal());
}
protected Principal loginImpl(HttpServletRequest request, HttpServletResponse response, ServletContext application,
String userName, String password) throws ServletException {
return loginImpl(userName, password);
}
public void setAppContextLocation(String appContextLocation) {
this.appContextLocation = appContextLocation;
}
public void setKey(String key) {
this.key = key;
}
}

View File

@ -1,7 +0,0 @@
<html>
<body>
Adapter to Resin web container.
<p>
</body>
</html>

View File

@ -1,261 +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.adapters.resin;
import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import java.security.Principal;
import javax.servlet.ServletException;
/**
* Tests {@link ResinAcegiAuthenticator}.
*
* @author Ben Alex
* @version $Id:ResinAcegiAuthenticatorTests.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class ResinAcegiAuthenticatorTests extends TestCase {
//~ Instance fields ================================================================================================
private final String ADAPTER_KEY = "my_key";
//~ Constructors ===================================================================================================
public ResinAcegiAuthenticatorTests() {
super();
}
public ResinAcegiAuthenticatorTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(ResinAcegiAuthenticatorTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAdapterAbortsIfAppContextDoesNotContainAnAuthenticationBean()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-invalid.xml");
adapter.setKey(ADAPTER_KEY);
try {
adapter.init();
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("Bean context must contain at least one bean of type AuthenticationManager",
expected.getMessage());
}
}
public void testAdapterAbortsIfNoAppContextSpecified()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setKey(ADAPTER_KEY);
try {
adapter.init();
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("appContextLocation must be defined", expected.getMessage());
}
adapter.setAppContextLocation("");
try {
adapter.init();
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("appContextLocation must be defined", expected.getMessage());
}
}
public void testAdapterAbortsIfNoKeySpecified() throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
try {
adapter.init();
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("key must be defined", expected.getMessage());
}
adapter.setKey("");
try {
adapter.init();
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("key must be defined", expected.getMessage());
}
}
public void testAdapterAbortsWithIncorrectApplicationContextLocation()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("FILE_DOES_NOT_EXIST");
adapter.setKey(ADAPTER_KEY);
try {
adapter.init();
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertTrue(expected.getMessage().startsWith("Cannot locate"));
}
}
public void testAdapterStartsUpSuccess() throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertTrue(true);
}
public void testAuthenticationFailsForIncorrectPassword()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertEquals(null, adapter.loginImpl("rod", "kangaroo"));
}
public void testAuthenticationFailsForIncorrectUserName()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertEquals(null, adapter.loginImpl("melissa", "koala"));
}
public void testAuthenticationSuccess() throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
Principal result = adapter.loginImpl("rod", "koala");
if (!(result instanceof PrincipalSpringSecurityUserToken)) {
fail("Should have returned PrincipalSpringSecurityUserToken");
}
PrincipalSpringSecurityUserToken castResult = (PrincipalSpringSecurityUserToken) result;
assertEquals("rod", castResult.getPrincipal());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_TELLER", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_SUPERVISOR", castResult.getAuthorities()[0].getAuthority());
assertEquals(ADAPTER_KEY.hashCode(), castResult.getKeyHash());
}
public void testAuthenticationSuccessUsingAlternateMethod()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
Principal result = adapter.loginImpl(null, null, null, "rod", "koala");
if (!(result instanceof PrincipalSpringSecurityUserToken)) {
fail("Should have returned PrincipalSpringSecurityUserToken");
}
PrincipalSpringSecurityUserToken castResult = (PrincipalSpringSecurityUserToken) result;
assertEquals("rod", castResult.getPrincipal());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_TELLER", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_SUPERVISOR", castResult.getAuthorities()[0].getAuthority());
assertEquals(ADAPTER_KEY.hashCode(), castResult.getKeyHash());
}
public void testAuthenticationWithNullPasswordHandledGracefully()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertEquals(null, adapter.loginImpl("rod", null));
}
public void testAuthenticationWithNullUserNameHandledGracefully()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertEquals(null, adapter.loginImpl(null, "koala"));
}
public void testGetters() throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
assertEquals(ADAPTER_KEY, adapter.getKey());
assertEquals("org/springframework/security/adapters/adaptertest-valid.xml", adapter.getAppContextLocation());
}
public void testHasRoleWithANullPrincipalFails() throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertTrue(!adapter.isUserInRole(null, null, null, null, "ROLE_ONE"));
}
public void testHasRoleWithAPrincipalTheAdapterDidNotCreateFails()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertTrue(!adapter.isUserInRole(null, null, null,
new Principal() {
public String getName() {
return "MockPrincipal";
}
}, "ROLE_ONE"));
}
public void testHasRoleWithPrincipalAcegiUserToken()
throws Exception {
PrincipalSpringSecurityUserToken token = new PrincipalSpringSecurityUserToken("KEY", "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
null);
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertTrue(adapter.isUserInRole(null, null, null, token, "ROLE_ONE"));
assertTrue(adapter.isUserInRole(null, null, null, token, "ROLE_ONE"));
assertTrue(!adapter.isUserInRole(null, null, null, token, "ROLE_WE_DO_NOT_HAVE"));
}
}