Functionality moved to new tests or mocks.

This commit is contained in:
Ben Alex 2004-04-02 12:18:58 +00:00
parent eaffc00fc4
commit a278db8df9
7 changed files with 0 additions and 1761 deletions

View File

@ -1,305 +0,0 @@
/* 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.
*/
package net.sf.acegisecurity;
import junit.framework.TestCase;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.SecureContext;
import net.sf.acegisecurity.context.SecureContextImpl;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
/**
* Tests {@link MethodDefinitionAttributes}.
*
* @author Cameron Braid
* @author Ben Alex
*/
public class MethodDefinitionAttributesTests extends TestCase {
//~ Instance fields ========================================================
ClassPathXmlApplicationContext applicationContext;
//~ Constructors ===========================================================
public MethodDefinitionAttributesTests(String a) {
super(a);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(MethodDefinitionAttributesTests.class);
}
public void testAttributesForInterfaceTargetObject()
throws Exception {
ConfigAttributeDefinition def1 = getConfigAttributeDefinition(ITargetObject.class,
"countLength", new Class[] {String.class});
Set set1 = toSet(def1);
assertTrue(set1.contains(new SecurityConfig("MOCK_INTERFACE")));
assertTrue(set1.contains(
new SecurityConfig("MOCK_INTERFACE_METHOD_COUNT_LENGTH")));
ConfigAttributeDefinition def2 = getConfigAttributeDefinition(ITargetObject.class,
"makeLowerCase", new Class[] {String.class});
Set set2 = toSet(def2);
assertTrue(set2.contains(new SecurityConfig("MOCK_INTERFACE")));
assertTrue(set2.contains(
new SecurityConfig("MOCK_INTERFACE_METHOD_MAKE_LOWER_CASE")));
ConfigAttributeDefinition def3 = getConfigAttributeDefinition(ITargetObject.class,
"makeUpperCase", new Class[] {String.class});
Set set3 = toSet(def3);
assertTrue(set3.contains(new SecurityConfig("MOCK_INTERFACE")));
assertTrue(set3.contains(
new SecurityConfig("MOCK_INTERFACE_METHOD_MAKE_UPPER_CASE")));
}
public void testAttributesForOtherTargetObject() throws Exception {
ConfigAttributeDefinition def1 = getConfigAttributeDefinition(OtherTargetObject.class,
"countLength", new Class[] {String.class});
Set set1 = toSet(def1);
assertTrue(set1.contains(new SecurityConfig("MOCK_INTERFACE")));
assertTrue(set1.contains(
new SecurityConfig("MOCK_INTERFACE_METHOD_COUNT_LENGTH")));
// Confirm MOCK_CLASS_METHOD_COUNT_LENGTH not added, as it's a String (not a ConfigAttribute)
// Confirm also MOCK_CLASS not added, as we return null for class
assertEquals(2, set1.size());
ConfigAttributeDefinition def2 = getConfigAttributeDefinition(OtherTargetObject.class,
"makeLowerCase", new Class[] {String.class});
Set set2 = toSet(def2);
assertTrue(set2.contains(new SecurityConfig("MOCK_INTERFACE")));
assertTrue(set2.contains(
new SecurityConfig("MOCK_INTERFACE_METHOD_MAKE_LOWER_CASE")));
assertTrue(set2.contains(
new SecurityConfig("MOCK_CLASS_METHOD_MAKE_LOWER_CASE")));
// Confirm MOCK_CLASS not added, as we return null for class
assertEquals(3, set2.size());
ConfigAttributeDefinition def3 = getConfigAttributeDefinition(OtherTargetObject.class,
"makeUpperCase", new Class[] {String.class});
Set set3 = toSet(def3);
assertTrue(set3.contains(new SecurityConfig("MOCK_INTERFACE")));
assertTrue(set3.contains(
new SecurityConfig("MOCK_INTERFACE_METHOD_MAKE_UPPER_CASE")));
assertTrue(set3.contains(new SecurityConfig("RUN_AS"))); // defined against interface
assertEquals(3, set3.size());
}
public void testAttributesForTargetObject() throws Exception {
ConfigAttributeDefinition def1 = getConfigAttributeDefinition(TargetObject.class,
"countLength", new Class[] {String.class});
Set set1 = toSet(def1);
assertTrue(set1.contains(new SecurityConfig("MOCK_INTERFACE")));
assertTrue(set1.contains(
new SecurityConfig("MOCK_INTERFACE_METHOD_COUNT_LENGTH")));
assertTrue(set1.contains(new SecurityConfig("MOCK_CLASS")));
// Confirm the MOCK_CLASS_METHOD_COUNT_LENGTH was not added, as it's not a ConfigAttribute
assertEquals(3, set1.size());
ConfigAttributeDefinition def2 = getConfigAttributeDefinition(TargetObject.class,
"makeLowerCase", new Class[] {String.class});
Set set2 = toSet(def2);
assertTrue(set2.contains(new SecurityConfig("MOCK_INTERFACE")));
assertTrue(set2.contains(
new SecurityConfig("MOCK_INTERFACE_METHOD_MAKE_LOWER_CASE")));
assertTrue(set2.contains(new SecurityConfig("MOCK_CLASS")));
assertTrue(set2.contains(
new SecurityConfig("MOCK_CLASS_METHOD_MAKE_LOWER_CASE")));
assertEquals(4, set2.size());
ConfigAttributeDefinition def3 = getConfigAttributeDefinition(TargetObject.class,
"makeUpperCase", new Class[] {String.class});
Set set3 = toSet(def3);
assertTrue(set3.contains(new SecurityConfig("MOCK_INTERFACE")));
assertTrue(set3.contains(
new SecurityConfig("MOCK_INTERFACE_METHOD_MAKE_UPPER_CASE")));
assertTrue(set3.contains(new SecurityConfig("MOCK_CLASS")));
assertTrue(set3.contains(
new SecurityConfig("MOCK_CLASS_METHOD_MAKE_UPPER_CASE")));
assertTrue(set3.contains(new SecurityConfig("RUN_AS")));
assertEquals(5, set3.size());
}
public void testMethodCallWithRunAsReplacement() throws Exception {
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_INTERFACE_METHOD_MAKE_UPPER_CASE")});
context.setAuthentication(token);
ContextHolder.setContext(context);
ITargetObject target = makeInterceptedTarget();
String result = target.makeUpperCase("hello");
assertEquals("HELLO net.sf.acegisecurity.MockRunAsAuthenticationToken true",
result);
ContextHolder.setContext(null);
}
public void testMethodCallWithoutRunAsReplacement()
throws Exception {
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_INTERFACE_METHOD_MAKE_LOWER_CASE")});
context.setAuthentication(token);
ContextHolder.setContext(context);
ITargetObject target = makeInterceptedTarget();
String result = target.makeLowerCase("HELLO");
assertEquals("hello net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken true",
result);
ContextHolder.setContext(null);
}
private ConfigAttributeDefinition getConfigAttributeDefinition(
Class clazz, String methodName, Class[] args) throws Exception {
final Method method = clazz.getMethod(methodName, args);
MethodDefinitionAttributes source = new MethodDefinitionAttributes();
source.setAttributes(new MockAttributes());
ConfigAttributeDefinition config = source.getAttributes(new MockMethodInvocation() {
public Method getMethod() {
return method;
}
});
return config;
}
private ITargetObject makeInterceptedTarget() {
String PREFIX = "beans.";
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
Properties p = new Properties();
p.setProperty(PREFIX + "authentication.class",
"net.sf.acegisecurity.MockAuthenticationManager");
p.setProperty(PREFIX + "accessDecision.class",
"net.sf.acegisecurity.MockAccessDecisionManager");
p.setProperty(PREFIX + "runAs.class",
"net.sf.acegisecurity.MockRunAsManager");
p.setProperty(PREFIX + "attributes.class",
"net.sf.acegisecurity.MockAttributes");
p.setProperty(PREFIX + "methodDefinitionSource.class",
"net.sf.acegisecurity.MethodDefinitionAttributes");
p.setProperty(PREFIX + "methodDefinitionSource.attributes(ref)",
"attributes");
p.setProperty(PREFIX + "securityInterceptor.class",
"net.sf.acegisecurity.SecurityInterceptor");
p.setProperty(PREFIX + "securityInterceptor.authenticationManager(ref)",
"authentication");
p.setProperty(PREFIX + "securityInterceptor.accessDecisionManager(ref)",
"accessDecision");
p.setProperty(PREFIX + "securityInterceptor.runAsManager(ref)", "runAs");
p.setProperty(PREFIX
+ "securityInterceptor.methodDefinitionSource(ref)",
"methodDefinitionSource");
p.setProperty(PREFIX + "targetObject.class",
"net.sf.acegisecurity.TargetObject");
p.setProperty(PREFIX + "target.class",
"org.springframework.aop.framework.ProxyFactoryBean");
p.setProperty(PREFIX + "target.proxyInterfaces",
"net.sf.acegisecurity.ITargetObject");
p.setProperty(PREFIX + "target.interceptorNames",
"securityInterceptor,targetObject");
(new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p,
PREFIX);
return (ITargetObject) lbf.getBean("target");
}
/**
* convert a <code>ConfigAttributeDefinition</code> into a set of
* <code>ConfigAttribute</code>(s)
*
* @param def the <code>ConfigAttributeDefinition</code> to cover
*
* @return a Set of <code>ConfigAttributes</code>
*/
private Set toSet(ConfigAttributeDefinition def) {
Set set = new HashSet();
Iterator i = def.getConfigAttributes();
while (i.hasNext()) {
ConfigAttribute a = (ConfigAttribute) i.next();
set.add(a);
}
return set;
}
//~ Inner Classes ==========================================================
private class MockMethodInvocation implements MethodInvocation {
public Object[] getArguments() {
throw new UnsupportedOperationException(
"mock method not implemented");
}
public Method getMethod() {
throw new UnsupportedOperationException(
"mock method not implemented");
}
public AccessibleObject getStaticPart() {
throw new UnsupportedOperationException(
"mock method not implemented");
}
public Object getThis() {
throw new UnsupportedOperationException(
"mock method not implemented");
}
public Object proceed() throws Throwable {
throw new UnsupportedOperationException(
"mock method not implemented");
}
}
}

View File

@ -1,215 +0,0 @@
/* 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.
*/
package net.sf.acegisecurity;
import junit.framework.TestCase;
import org.aopalliance.intercept.MethodInvocation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.util.Iterator;
/**
* Tests {@link MethodDefinitionSourceEditor}.
*
* @author Ben Alex
* @version $Id$
*/
public class MethodDefinitionSourceEditorTests extends TestCase {
//~ Constructors ===========================================================
public MethodDefinitionSourceEditorTests() {
super();
}
public MethodDefinitionSourceEditorTests(String arg0) {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(MethodDefinitionSourceEditorTests.class);
}
public void testClassNameNotFoundResultsInException() {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
try {
editor.setAsText("net.sf.acegisecurity.DOES_NOT_EXIST_NAME=FOO,BAR");
fail("Should have given IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testClassNameNotInProperFormatResultsInException() {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
try {
editor.setAsText("DOES_NOT_EXIST_NAME=FOO,BAR");
fail("Should have given IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testClassNameValidButMethodNameInvalidResultsInException() {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
try {
editor.setAsText(
"net.sf.acegisecurity.TargetObject.INVALID_METHOD=FOO,BAR");
fail("Should have given IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testEmptyStringReturnsEmptyMap() {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
editor.setAsText("");
MethodDefinitionMap map = (MethodDefinitionMap) editor.getValue();
assertEquals(0, map.getMethodMapSize());
}
public void testIterator() {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
editor.setAsText(
"net.sf.acegisecurity.TargetObject.countLength=ROLE_ONE,ROLE_TWO,RUN_AS_ENTRY\r\nnet.sf.acegisecurity.TargetObject.make*=ROLE_NINE,ROLE_SUPERVISOR");
MethodDefinitionMap map = (MethodDefinitionMap) editor.getValue();
Iterator iter = map.getConfigAttributeDefinitions();
int counter = 0;
while (iter.hasNext()) {
iter.next();
counter++;
}
assertEquals(3, counter);
}
public void testMultiMethodParsing() {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
editor.setAsText(
"net.sf.acegisecurity.TargetObject.countLength=ROLE_ONE,ROLE_TWO,RUN_AS_ENTRY\r\nnet.sf.acegisecurity.TargetObject.make*=ROLE_NINE,ROLE_SUPERVISOR");
MethodDefinitionMap map = (MethodDefinitionMap) editor.getValue();
assertEquals(3, map.getMethodMapSize());
}
public void testMultiMethodParsingWhereLaterMethodsOverrideEarlierMethods()
throws Exception {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
editor.setAsText(
"net.sf.acegisecurity.TargetObject.*=ROLE_GENERAL\r\nnet.sf.acegisecurity.TargetObject.makeLower*=ROLE_LOWER\r\nnet.sf.acegisecurity.TargetObject.make*=ROLE_MAKE\r\nnet.sf.acegisecurity.TargetObject.makeUpper*=ROLE_UPPER");
MethodDefinitionMap map = (MethodDefinitionMap) editor.getValue();
assertEquals(4, map.getMethodMapSize());
ConfigAttributeDefinition returnedMakeLower = map.getAttributes(new MockMethodInvocation(
TargetObject.class, "makeLowerCase",
new Class[] {String.class}));
ConfigAttributeDefinition expectedMakeLower = new ConfigAttributeDefinition();
expectedMakeLower.addConfigAttribute(new SecurityConfig("ROLE_LOWER"));
assertEquals(expectedMakeLower, returnedMakeLower);
ConfigAttributeDefinition returnedMakeUpper = map.getAttributes(new MockMethodInvocation(
TargetObject.class, "makeUpperCase",
new Class[] {String.class}));
ConfigAttributeDefinition expectedMakeUpper = new ConfigAttributeDefinition();
expectedMakeUpper.addConfigAttribute(new SecurityConfig("ROLE_UPPER"));
assertEquals(expectedMakeUpper, returnedMakeUpper);
ConfigAttributeDefinition returnedCountLength = map.getAttributes(new MockMethodInvocation(
TargetObject.class, "countLength",
new Class[] {String.class}));
ConfigAttributeDefinition expectedCountLength = new ConfigAttributeDefinition();
expectedCountLength.addConfigAttribute(new SecurityConfig(
"ROLE_GENERAL"));
assertEquals(expectedCountLength, returnedCountLength);
}
public void testNullReturnsEmptyMap() {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
editor.setAsText(null);
MethodDefinitionMap map = (MethodDefinitionMap) editor.getValue();
assertEquals(0, map.getMethodMapSize());
}
public void testSingleMethodParsing() throws Exception {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
editor.setAsText(
"net.sf.acegisecurity.TargetObject.countLength=ROLE_ONE,ROLE_TWO,RUN_AS_ENTRY");
MethodDefinitionMap map = (MethodDefinitionMap) editor.getValue();
ConfigAttributeDefinition returnedCountLength = map.getAttributes(new MockMethodInvocation(
TargetObject.class, "countLength",
new Class[] {String.class}));
ConfigAttributeDefinition expectedCountLength = new ConfigAttributeDefinition();
expectedCountLength.addConfigAttribute(new SecurityConfig("ROLE_ONE"));
expectedCountLength.addConfigAttribute(new SecurityConfig("ROLE_TWO"));
expectedCountLength.addConfigAttribute(new SecurityConfig(
"RUN_AS_ENTRY"));
assertEquals(expectedCountLength, returnedCountLength);
}
//~ Inner Classes ==========================================================
private class MockMethodInvocation implements MethodInvocation {
Method method;
public MockMethodInvocation(Class clazz, String methodName,
Class[] parameterTypes) throws NoSuchMethodException {
method = clazz.getMethod(methodName, parameterTypes);
}
private MockMethodInvocation() {
super();
}
public Object[] getArguments() {
return null;
}
public Method getMethod() {
return method;
}
public AccessibleObject getStaticPart() {
return null;
}
public Object getThis() {
return null;
}
public Object proceed() throws Throwable {
return null;
}
}
}

View File

@ -1,155 +0,0 @@
/* 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.
*/
package net.sf.acegisecurity;
import org.springframework.metadata.Attributes;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* Used by the {@link MethodDefinitionAttributesTests}.
*
* @author Cameron Braid
* @author Ben Alex
*/
public class MockAttributes implements Attributes {
//~ Instance fields ========================================================
List classAttributes = Arrays.asList(new SecurityConfig[] {new SecurityConfig(
"MOCK_CLASS")});
List classMethodAttributesCountLength = Arrays.asList(new String[] {new String(
"MOCK_CLASS_METHOD_COUNT_LENGTH")});
List classMethodAttributesMakeLowerCase = Arrays.asList(new SecurityConfig[] {new SecurityConfig(
"MOCK_CLASS_METHOD_MAKE_LOWER_CASE")});
List classMethodAttributesMakeUpperCase = Arrays.asList(new SecurityConfig[] {new SecurityConfig(
"MOCK_CLASS_METHOD_MAKE_UPPER_CASE")});
List interfaceAttributes = Arrays.asList(new SecurityConfig[] {new SecurityConfig(
"MOCK_INTERFACE")});
List interfaceMethodAttributesCountLength = Arrays.asList(new SecurityConfig[] {new SecurityConfig(
"MOCK_INTERFACE_METHOD_COUNT_LENGTH")});
List interfaceMethodAttributesMakeLowerCase = Arrays.asList(new SecurityConfig[] {new SecurityConfig(
"MOCK_INTERFACE_METHOD_MAKE_LOWER_CASE")});
List interfaceMethodAttributesMakeUpperCase = Arrays.asList(new SecurityConfig[] {new SecurityConfig(
"MOCK_INTERFACE_METHOD_MAKE_UPPER_CASE"), new SecurityConfig(
"RUN_AS")});
//~ Methods ================================================================
public Collection getAttributes(Class clazz) {
// Emphasise we return null for OtherTargetObject
if (clazz.equals(OtherTargetObject.class)) {
return null;
}
// interface
if (clazz.equals(ITargetObject.class)) {
return interfaceAttributes;
}
// class
if (clazz.equals(TargetObject.class)) {
return classAttributes;
}
return null;
}
public Collection getAttributes(Method method) {
// interface
if (method.getDeclaringClass().equals(ITargetObject.class)) {
if (method.getName().equals("countLength")) {
return interfaceMethodAttributesCountLength;
}
if (method.getName().equals("makeLowerCase")) {
return interfaceMethodAttributesMakeLowerCase;
}
if (method.getName().equals("makeUpperCase")) {
return interfaceMethodAttributesMakeUpperCase;
}
if (method.getName().equals("publicMakeLowerCase")) {
throw new UnsupportedOperationException(
"mock support not implemented");
}
}
// class
if (method.getDeclaringClass().equals(TargetObject.class)) {
if (method.getName().equals("countLength")) {
return classMethodAttributesCountLength;
}
if (method.getName().equals("makeLowerCase")) {
return classMethodAttributesMakeLowerCase;
}
if (method.getName().equals("makeUpperCase")) {
return classMethodAttributesMakeUpperCase;
}
if (method.getName().equals("publicMakeLowerCase")) {
throw new UnsupportedOperationException(
"mock support not implemented");
}
}
// other target object
if (method.getDeclaringClass().equals(OtherTargetObject.class)) {
if (method.getName().equals("countLength")) {
return classMethodAttributesCountLength;
}
if (method.getName().equals("makeLowerCase")) {
return classMethodAttributesMakeLowerCase;
}
if (method.getName().equals("makeUpperCase")) {
return null; // NB
}
if (method.getName().equals("publicMakeLowerCase")) {
throw new UnsupportedOperationException(
"mock support not implemented");
}
}
return null;
}
public Collection getAttributes(Class arg0, Class arg1) {
throw new UnsupportedOperationException("mock method not implemented");
}
public Collection getAttributes(Field arg0, Class arg1) {
throw new UnsupportedOperationException("mock method not implemented");
}
public Collection getAttributes(Field arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
public Collection getAttributes(Method arg0, Class arg1) {
throw new UnsupportedOperationException("mock method not implemented");
}
}

View File

@ -1,420 +0,0 @@
/* 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.
*/
package net.sf.acegisecurity;
import junit.framework.TestCase;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.ContextImpl;
import net.sf.acegisecurity.context.SecureContext;
import net.sf.acegisecurity.context.SecureContextImpl;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
/**
* Tests {@link SecurityInterceptor}.
*
* @author Ben Alex
* @version $Id$
*/
public class SecurityInterceptorTests extends TestCase {
//~ Constructors ===========================================================
public SecurityInterceptorTests() {
super();
}
public SecurityInterceptorTests(String arg0) {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(SecurityInterceptorTests.class);
}
public void testCallingAPublicMethodFacadeWillNotRepeatSecurityChecksWhenPassedToTheSecuredMethodItFronts()
throws Exception {
ITargetObject target = makeInterceptedTarget();
String result = target.publicMakeLowerCase("HELLO");
assertEquals("hello ContextHolder Not Security Aware", result);
ContextHolder.setContext(null);
}
public void testCallingAPublicMethodWhenPresentingASecureContextButWithoutAnyAuthenticationObject()
throws Exception {
SecureContext context = new SecureContextImpl();
ContextHolder.setContext(context);
ITargetObject target = makeInterceptedTarget();
String result = target.publicMakeLowerCase("HELLO");
assertEquals("hello Authentication empty", result);
ContextHolder.setContext(null);
}
public void testCallingAPublicMethodWhenPresentingAnAuthenticationObjectWillProperlySetItsIsAuthenticatedProperty()
throws Exception {
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_THIS_IS_NOT_REQUIRED_AS_IT_IS_PUBLIC")});
assertTrue(!token.isAuthenticated());
context.setAuthentication(token);
ContextHolder.setContext(context);
ITargetObject target = makeInterceptedTarget();
String result = target.publicMakeLowerCase("HELLO");
assertEquals("hello net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken false",
result);
ContextHolder.setContext(null);
}
public void testDeniesWhenAppropriate() throws Exception {
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_NO_BENEFIT_TO_THIS_GRANTED_AUTHORITY")});
context.setAuthentication(token);
ContextHolder.setContext(context);
ITargetObject target = makeInterceptedTarget();
try {
target.makeUpperCase("HELLO");
fail("Should have thrown AccessDeniedException");
} catch (AccessDeniedException expected) {
assertTrue(true);
}
ContextHolder.setContext(null);
}
public void testGetters() {
MockAccessDecisionManager accessDecision = new MockAccessDecisionManager();
MockRunAsManager runAs = new MockRunAsManager();
MockAuthenticationManager authManager = new MockAuthenticationManager();
MockMethodDefinitionSource methodSource = new MockMethodDefinitionSource(false,
true);
SecurityInterceptor si = new SecurityInterceptor();
si.setAccessDecisionManager(accessDecision);
si.setRunAsManager(runAs);
si.setAuthenticationManager(authManager);
si.setMethodDefinitionSource(methodSource);
assertEquals(accessDecision, si.getAccessDecisionManager());
assertEquals(runAs, si.getRunAsManager());
assertEquals(authManager, si.getAuthenticationManager());
assertEquals(methodSource, si.getMethodDefinitionSource());
}
public void testMethodCallWithRunAsReplacement() throws Exception {
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_UPPER")});
context.setAuthentication(token);
ContextHolder.setContext(context);
ITargetObject target = makeInterceptedTarget();
String result = target.makeUpperCase("hello");
assertEquals("HELLO net.sf.acegisecurity.MockRunAsAuthenticationToken true",
result);
ContextHolder.setContext(null);
}
public void testMethodCallWithoutRunAsReplacement()
throws Exception {
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_LOWER")});
assertTrue(!token.isAuthenticated());
context.setAuthentication(token);
ContextHolder.setContext(context);
ITargetObject target = makeInterceptedTarget();
String result = target.makeLowerCase("HELLO");
// Note we check the isAuthenticated becomes true in following line
assertEquals("hello net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken true",
result);
ContextHolder.setContext(null);
}
public void testRejectionOfEmptyContextHolder() throws Exception {
ITargetObject target = makeInterceptedTarget();
try {
target.makeUpperCase("hello");
fail(
"Should have thrown AuthenticationCredentialsNotFoundException");
} catch (AuthenticationCredentialsNotFoundException expected) {
assertTrue(true);
}
}
public void testRejectionOfNonSecureContextOnContextHolder()
throws Exception {
ContextHolder.setContext(new ContextImpl());
ITargetObject target = makeInterceptedTarget();
try {
target.makeUpperCase("hello");
fail(
"Should have thrown AuthenticationCredentialsNotFoundException");
} catch (AuthenticationCredentialsNotFoundException expected) {
assertTrue(true);
}
ContextHolder.setContext(null);
}
public void testRejectionOfSecureContextThatContainsNoAuthenticationObject()
throws Exception {
ContextHolder.setContext(new SecureContextImpl());
ITargetObject target = makeInterceptedTarget();
try {
target.makeUpperCase("hello");
fail(
"Should have thrown AuthenticationCredentialsNotFoundException");
} catch (AuthenticationCredentialsNotFoundException expected) {
assertTrue(true);
}
ContextHolder.setContext(null);
}
public void testStartupCheckForAccessDecisionManager() {
SecurityInterceptor si = new SecurityInterceptor();
si.setRunAsManager(new MockRunAsManager());
si.setAuthenticationManager(new MockAuthenticationManager());
si.setMethodDefinitionSource(new MockMethodDefinitionSource(false, true));
try {
si.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("An AccessDecisionManager is required",
expected.getMessage());
}
}
public void testStartupCheckForAuthenticationManager() {
SecurityInterceptor si = new SecurityInterceptor();
si.setAccessDecisionManager(new MockAccessDecisionManager());
si.setRunAsManager(new MockRunAsManager());
si.setMethodDefinitionSource(new MockMethodDefinitionSource(false, true));
try {
si.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("An AuthenticationManager is required",
expected.getMessage());
}
}
public void testStartupCheckForMethodDefinitionSource() {
SecurityInterceptor si = new SecurityInterceptor();
si.setAccessDecisionManager(new MockAccessDecisionManager());
si.setRunAsManager(new MockRunAsManager());
si.setAuthenticationManager(new MockAuthenticationManager());
try {
si.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("A MethodDefinitionSource is required",
expected.getMessage());
}
}
public void testStartupCheckForRunAsManager() {
SecurityInterceptor si = new SecurityInterceptor();
si.setAccessDecisionManager(new MockAccessDecisionManager());
si.setAuthenticationManager(new MockAuthenticationManager());
si.setMethodDefinitionSource(new MockMethodDefinitionSource(false, true));
try {
si.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("A RunAsManager is required", expected.getMessage());
}
}
public void testValidationFailsIfInvalidAttributePresented() {
SecurityInterceptor si = new SecurityInterceptor();
si.setAccessDecisionManager(new MockAccessDecisionManager());
si.setRunAsManager(new MockRunAsManager());
si.setAuthenticationManager(new MockAuthenticationManager());
assertTrue(si.isValidateConfigAttributes()); // check default
si.setMethodDefinitionSource(new MockMethodDefinitionSource(true, true));
try {
si.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("Unsupported configuration attributes: [ANOTHER_INVALID, INVALID_ATTRIBUTE]",
expected.getMessage());
}
}
public void testValidationNotAttemptedIfIsValidateConfigAttributesSetToFalse() {
SecurityInterceptor si = new SecurityInterceptor();
si.setAccessDecisionManager(new MockAccessDecisionManager());
si.setRunAsManager(new MockRunAsManager());
si.setAuthenticationManager(new MockAuthenticationManager());
assertTrue(si.isValidateConfigAttributes()); // check default
si.setValidateConfigAttributes(false);
assertTrue(!si.isValidateConfigAttributes()); // check changed
si.setMethodDefinitionSource(new MockMethodDefinitionSource(true, true));
si.afterPropertiesSet();
assertTrue(true);
}
public void testValidationNotAttemptedIfMethodDefinitionSourceCannotReturnIterator() {
SecurityInterceptor si = new SecurityInterceptor();
si.setAccessDecisionManager(new MockAccessDecisionManager());
si.setRunAsManager(new MockRunAsManager());
si.setAuthenticationManager(new MockAuthenticationManager());
assertTrue(si.isValidateConfigAttributes()); // check default
si.setMethodDefinitionSource(new MockMethodDefinitionSource(true, false));
si.afterPropertiesSet();
assertTrue(true);
}
private ITargetObject makeInterceptedTarget() {
String PREFIX = "beans.";
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
Properties p = new Properties();
p.setProperty(PREFIX + "authentication.class",
"net.sf.acegisecurity.MockAuthenticationManager");
p.setProperty(PREFIX + "accessDecision.class",
"net.sf.acegisecurity.MockAccessDecisionManager");
p.setProperty(PREFIX + "runAs.class",
"net.sf.acegisecurity.MockRunAsManager");
p.setProperty(PREFIX + "securityInterceptor.class",
"net.sf.acegisecurity.SecurityInterceptor");
p.setProperty(PREFIX + "securityInterceptor.authenticationManager(ref)",
"authentication");
p.setProperty(PREFIX + "securityInterceptor.accessDecisionManager(ref)",
"accessDecision");
p.setProperty(PREFIX + "securityInterceptor.runAsManager(ref)", "runAs");
p.setProperty(PREFIX + "securityInterceptor.methodDefinitionSource",
"net.sf.acegisecurity.ITargetObject.makeLower*=MOCK_LOWER\r\nnet.sf.acegisecurity.ITargetObject.makeUpper*=MOCK_UPPER,RUN_AS");
p.setProperty(PREFIX + "targetObject.class",
"net.sf.acegisecurity.TargetObject");
p.setProperty(PREFIX + "target.class",
"org.springframework.aop.framework.ProxyFactoryBean");
p.setProperty(PREFIX + "target.proxyInterfaces",
"net.sf.acegisecurity.ITargetObject");
p.setProperty(PREFIX + "target.interceptorNames",
"securityInterceptor,targetObject");
(new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p,
PREFIX);
return (ITargetObject) lbf.getBean("target");
}
//~ Inner Classes ==========================================================
private class MockMethodDefinitionSource implements MethodDefinitionSource {
private List list;
private boolean returnAnIterator;
public MockMethodDefinitionSource(boolean includeInvalidAttributes,
boolean returnAnIteratorWhenRequested) {
returnAnIterator = returnAnIteratorWhenRequested;
list = new Vector();
ConfigAttributeDefinition def1 = new ConfigAttributeDefinition();
def1.addConfigAttribute(new SecurityConfig("MOCK_LOWER"));
list.add(def1);
if (includeInvalidAttributes) {
ConfigAttributeDefinition def2 = new ConfigAttributeDefinition();
def2.addConfigAttribute(new SecurityConfig("MOCK_LOWER"));
def2.addConfigAttribute(new SecurityConfig("INVALID_ATTRIBUTE"));
list.add(def2);
}
ConfigAttributeDefinition def3 = new ConfigAttributeDefinition();
def3.addConfigAttribute(new SecurityConfig("MOCK_UPPER"));
def3.addConfigAttribute(new SecurityConfig("RUN_AS"));
list.add(def3);
if (includeInvalidAttributes) {
ConfigAttributeDefinition def4 = new ConfigAttributeDefinition();
def4.addConfigAttribute(new SecurityConfig("MOCK_SOMETHING"));
def4.addConfigAttribute(new SecurityConfig("ANOTHER_INVALID"));
list.add(def4);
}
}
private MockMethodDefinitionSource() {
super();
}
public ConfigAttributeDefinition getAttributes(
MethodInvocation invocation) {
throw new UnsupportedOperationException(
"mock method not implemented");
}
public Iterator getConfigAttributeDefinitions() {
if (returnAnIterator) {
return list.iterator();
} else {
return null;
}
}
}
}

View File

@ -1,260 +0,0 @@
/* 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.
*/
package net.sf.acegisecurity.adapters;
import junit.framework.TestCase;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.context.Context;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.SecureContext;
import net.sf.acegisecurity.context.SecureContextImpl;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* Tests {@link AbstractIntegrationFilter}.
*
* @author Ben Alex
* @version $Id$
*/
public class AbstractIntegrationFilterTests extends TestCase {
//~ Constructors ===========================================================
public AbstractIntegrationFilterTests() {
super();
}
public AbstractIntegrationFilterTests(String arg0) {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(AbstractIntegrationFilterTests.class);
}
public void testContextHolderContentsPreserved() throws Exception {
PrincipalAcegiUserToken principal = new PrincipalAcegiUserToken("key",
"someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_ROLE")});
MockAbstractIntegrationFilterImpl filter = new MockAbstractIntegrationFilterImpl(principal);
MockFilterChain chain = new MockFilterChain(true, principal);
MockSecureContextImpl secureContext = new MockSecureContextImpl(
"FOO_BAR");
ContextHolder.setContext(secureContext);
assertEquals(secureContext, ContextHolder.getContext());
executeFilterInContainerSimulator(filter, null, null, chain);
MockSecureContextImpl after = (MockSecureContextImpl) ContextHolder
.getContext();
assertEquals(secureContext.getInfo(), after.getInfo());
ContextHolder.setContext(null);
}
public void testContextHolderHasAuthenticationRemoved()
throws Exception {
PrincipalAcegiUserToken principal = new PrincipalAcegiUserToken("key",
"someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_ROLE")});
MockAbstractIntegrationFilterImpl filter = new MockAbstractIntegrationFilterImpl(principal);
MockFilterChain chain = new MockFilterChain(true, principal);
SecureContext secureContext = new SecureContextImpl();
secureContext.setAuthentication(principal);
ContextHolder.setContext(secureContext);
assertEquals(secureContext, ContextHolder.getContext());
executeFilterInContainerSimulator(filter, null, null, chain);
SecureContext after = (SecureContext) ContextHolder.getContext();
assertEquals(null, after.getAuthentication());
ContextHolder.setContext(null);
}
public void testIgnoredWhenConcreteClassReturnsANonAuthenticationObject()
throws Exception {
MockPrincipal principal = new MockPrincipal();
MockAbstractIntegrationFilterImpl filter = new MockAbstractIntegrationFilterImpl(principal);
MockFilterChain chain = new MockFilterChain(false, null);
Context before = ContextHolder.getContext();
if (before != null) {
if (before instanceof SecureContext) {
assertEquals(null, ((SecureContext) before).getAuthentication());
}
}
executeFilterInContainerSimulator(filter, null, null, chain);
Context after = ContextHolder.getContext();
if (after != null) {
if (after instanceof SecureContext) {
assertEquals(null, ((SecureContext) after).getAuthentication());
}
}
}
public void testIgnoredWhenConcreteClassReturnsNullAuthenticationObject()
throws Exception {
MockAbstractIntegrationFilterImpl filter = new MockAbstractIntegrationFilterImpl(null);
MockFilterChain chain = new MockFilterChain(false, null);
Context before = ContextHolder.getContext();
if (before != null) {
if (before instanceof SecureContext) {
assertEquals(null, ((SecureContext) before).getAuthentication());
}
}
executeFilterInContainerSimulator(filter, null, null, chain);
Context after = ContextHolder.getContext();
if (after != null) {
if (after instanceof SecureContext) {
assertEquals(null, ((SecureContext) after).getAuthentication());
}
}
}
public void testSuccessWhenConcreteClassReturnsValidAuthenticationObject()
throws Exception {
PrincipalAcegiUserToken principal = new PrincipalAcegiUserToken("key",
"someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_ROLE")});
MockAbstractIntegrationFilterImpl filter = new MockAbstractIntegrationFilterImpl(principal);
MockFilterChain chain = new MockFilterChain(true, principal);
Context before = ContextHolder.getContext();
if (before != null) {
if (before instanceof SecureContext) {
assertEquals(null, ((SecureContext) before).getAuthentication());
}
}
executeFilterInContainerSimulator(filter, null, null, chain);
Context after = ContextHolder.getContext();
if (after != null) {
if (after instanceof SecureContext) {
assertEquals(null, ((SecureContext) after).getAuthentication());
}
}
}
private void executeFilterInContainerSimulator(Filter filter,
ServletRequest request, ServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
filter.init(null);
filter.doFilter(request, response, filterChain);
filter.destroy();
}
//~ Inner Classes ==========================================================
private class MockAbstractIntegrationFilterImpl
extends AbstractIntegrationFilter {
private Object extractFromContainerResult;
public MockAbstractIntegrationFilterImpl(
Object extractFromContainerResult) {
this.extractFromContainerResult = extractFromContainerResult;
}
private MockAbstractIntegrationFilterImpl() {
super();
}
public Object extractFromContainer(ServletRequest request) {
return this.extractFromContainerResult;
}
}
private class MockFilterChain implements FilterChain {
private Authentication expectedAuthenticationObjectInContextHolder;
private boolean expectContextHolderContainSecureContext = false;
public MockFilterChain(
boolean expectContextHolderContainSecureContext,
Authentication expectedAuthenticationObjectInContextHolder) {
if ((expectedAuthenticationObjectInContextHolder != null)
&& !expectContextHolderContainSecureContext) {
throw new IllegalArgumentException(
"If an Authentication object is expected, the ContextHolder should contain a SecureContext");
}
this.expectContextHolderContainSecureContext = expectContextHolderContainSecureContext;
this.expectedAuthenticationObjectInContextHolder = expectedAuthenticationObjectInContextHolder;
}
private MockFilterChain() {
super();
}
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if (expectContextHolderContainSecureContext) {
Context context = ContextHolder.getContext();
if (!(context instanceof SecureContext)) {
fail("ContextHolder should have contained SecureContext");
}
} else {
if (ContextHolder.getContext() != null) {
fail("ContextHolder should have been null but wasn't");
}
}
}
}
private class MockSecureContextImpl extends SecureContextImpl {
private String info;
public MockSecureContextImpl(String info) {
this.info = info;
}
private MockSecureContextImpl() {
super();
}
public String getInfo() {
return this.info;
}
}
}

View File

@ -1,149 +0,0 @@
/* 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.
*/
package net.sf.acegisecurity.adapters;
import junit.framework.TestCase;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.adapters.jboss.JbossIntegrationFilter;
import net.sf.acegisecurity.adapters.jboss.MockInitialContext;
import net.sf.acegisecurity.adapters.jboss.MockJbossIntegrationFilter;
import org.jboss.security.SimplePrincipal;
import java.security.Principal;
import java.util.HashSet;
import java.util.Set;
import javax.naming.Context;
import javax.security.auth.Subject;
/**
* Tests {@link AutoIntegrationFilter}.
*
* @author Ben Alex
* @version $Id$
*/
public class AutoIntegrationFilterTests extends TestCase {
//~ Constructors ===========================================================
public AutoIntegrationFilterTests() {
super();
}
public AutoIntegrationFilterTests(String arg0) {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(AutoIntegrationFilterTests.class);
}
public void testDetectsAuthenticationObjectInHttpRequest() {
AutoIntegrationFilter filter = new AutoIntegrationFilter();
PrincipalAcegiUserToken principal = new PrincipalAcegiUserToken("key",
"someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_ROLE")});
Object result = filter.extractFromContainer(new MockHttpServletRequest(
principal));
if (!(result instanceof PrincipalAcegiUserToken)) {
fail("Should have returned PrincipalAcegiUserToken");
}
PrincipalAcegiUserToken castResult = (PrincipalAcegiUserToken) result;
assertEquals(principal, result);
}
public void testDetectsAuthenticationObjectInJboss() {
// Prepare a mock Jboss environment reflecting completed authentication
PrincipalAcegiUserToken principal = new PrincipalAcegiUserToken("key",
"someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_ROLE")});
Context context = new MockInitialContext(makeIntoSubject(principal));
JbossIntegrationFilter jbossFilter = new MockJbossIntegrationFilter(context);
// Create a SimplePrincipal, which is what JBoss places into HttpRequest
SimplePrincipal simplePrincipal = new SimplePrincipal("TEST");
// Now try to extract authentication information via our mock AutoIntegrationFilter
AutoIntegrationFilter filter = new MockAutoIntegrationFilterJboss(jbossFilter);
Object result = filter.extractFromContainer(new MockHttpServletRequest(
simplePrincipal));
System.out.println(result);
if (!(result instanceof PrincipalAcegiUserToken)) {
fail("Should have returned PrincipalAcegiUserToken");
}
PrincipalAcegiUserToken castResult = (PrincipalAcegiUserToken) result;
assertEquals(principal, result);
}
public void testHandlesIfHttpRequestIsNullForSomeReason() {
AutoIntegrationFilter filter = new AutoIntegrationFilter();
assertEquals(null, filter.extractFromContainer(null));
}
public void testHandlesIfThereIsNoPrincipal() {
AutoIntegrationFilter filter = new AutoIntegrationFilter();
assertEquals(null,
filter.extractFromContainer(new MockHttpServletRequest(null)));
}
public void testReturnsNullIfNonAuthenticationObjectInHttpRequest() {
AutoIntegrationFilter filter = new AutoIntegrationFilter();
assertEquals(null,
filter.extractFromContainer(
new MockHttpServletRequest(new MockPrincipal())));
}
private Subject makeIntoSubject(Principal principal) {
Set principals = new HashSet();
principals.add(principal);
return new Subject(false, principals, new HashSet(), new HashSet());
}
//~ Inner Classes ==========================================================
private class MockAutoIntegrationFilterJboss extends AutoIntegrationFilter {
private JbossIntegrationFilter filter;
public MockAutoIntegrationFilterJboss(JbossIntegrationFilter filter) {
this.filter = filter;
}
private MockAutoIntegrationFilterJboss() {
super();
}
protected JbossIntegrationFilter getJbossIntegrationFilter() {
return this.filter;
}
}
}

View File

@ -1,257 +0,0 @@
/* 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.
*/
package net.sf.acegisecurity.adapters;
import java.io.BufferedReader;
import java.io.IOException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* Mocks a <code>HttpServletRequest</code> and provides the
* <code>getUserPrincipal()</code> method.
*
* @author Ben Alex
* @version $Id$
*/
public class MockHttpServletRequest implements HttpServletRequest {
//~ Instance fields ========================================================
private Principal principal;
//~ Constructors ===========================================================
public MockHttpServletRequest(Principal principal) {
this.principal = principal;
}
private MockHttpServletRequest() {
super();
}
//~ Methods ================================================================
public void setAttribute(String arg0, Object arg1) {
throw new UnsupportedOperationException("mock method not implemented");
}
public Object getAttribute(String arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
public Enumeration getAttributeNames() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getAuthType() {
throw new UnsupportedOperationException("mock method not implemented");
}
public void setCharacterEncoding(String arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getCharacterEncoding() {
throw new UnsupportedOperationException("mock method not implemented");
}
public int getContentLength() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getContentType() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getContextPath() {
throw new UnsupportedOperationException("mock method not implemented");
}
public Cookie[] getCookies() {
throw new UnsupportedOperationException("mock method not implemented");
}
public long getDateHeader(String arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getHeader(String arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
public Enumeration getHeaderNames() {
throw new UnsupportedOperationException("mock method not implemented");
}
public Enumeration getHeaders(String arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
public ServletInputStream getInputStream() throws IOException {
throw new UnsupportedOperationException("mock method not implemented");
}
public int getIntHeader(String arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
public Locale getLocale() {
throw new UnsupportedOperationException("mock method not implemented");
}
public Enumeration getLocales() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getMethod() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getParameter(String arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
public Map getParameterMap() {
throw new UnsupportedOperationException("mock method not implemented");
}
public Enumeration getParameterNames() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String[] getParameterValues(String arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getPathInfo() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getPathTranslated() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getProtocol() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getQueryString() {
throw new UnsupportedOperationException("mock method not implemented");
}
public BufferedReader getReader() throws IOException {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getRealPath(String arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getRemoteAddr() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getRemoteHost() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getRemoteUser() {
throw new UnsupportedOperationException("mock method not implemented");
}
public RequestDispatcher getRequestDispatcher(String arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getRequestURI() {
throw new UnsupportedOperationException("mock method not implemented");
}
public StringBuffer getRequestURL() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getRequestedSessionId() {
throw new UnsupportedOperationException("mock method not implemented");
}
public boolean isRequestedSessionIdFromCookie() {
throw new UnsupportedOperationException("mock method not implemented");
}
public boolean isRequestedSessionIdFromURL() {
throw new UnsupportedOperationException("mock method not implemented");
}
public boolean isRequestedSessionIdFromUrl() {
throw new UnsupportedOperationException("mock method not implemented");
}
public boolean isRequestedSessionIdValid() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getScheme() {
throw new UnsupportedOperationException("mock method not implemented");
}
public boolean isSecure() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getServerName() {
throw new UnsupportedOperationException("mock method not implemented");
}
public int getServerPort() {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getServletPath() {
throw new UnsupportedOperationException("mock method not implemented");
}
public HttpSession getSession(boolean arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
public HttpSession getSession() {
throw new UnsupportedOperationException("mock method not implemented");
}
public boolean isUserInRole(String arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
public Principal getUserPrincipal() {
return this.principal;
}
public void removeAttribute(String arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
}