SEC-97: Format Acegi Security source code in accordance with latest Jalopy configuration.

This commit is contained in:
Ben Alex
2006-05-23 13:38:33 +00:00
parent 49800018e9
commit ab12817b7a
654 changed files with 17379 additions and 21566 deletions

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -16,8 +16,10 @@
package org.acegisecurity;
import junit.framework.TestCase;
import org.acegisecurity.providers.TestingAuthenticationToken;
/**
* Tests {@link AbstractAuthenticationManager}.
*
@@ -25,7 +27,7 @@ import org.acegisecurity.providers.TestingAuthenticationToken;
* @version $Id$
*/
public class AbstractAuthenticationManagerTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AbstractAuthenticationManagerTests() {
super();
@@ -35,17 +37,29 @@ public class AbstractAuthenticationManagerTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public void testDetailsAreSetOnAuthenticationTokenIfNotAlreadySetByProvider() {
AuthenticationManager authMgr = createAuthenticationManager(null);
Object details = new Object();
/**
* Creates an AuthenticationManager which will return a token with the given details object set on it.
*
* @param resultDetails DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private AuthenticationManager createAuthenticationManager(final Object resultDetails) {
return new AbstractAuthenticationManager() {
protected Authentication doAuthentication(Authentication authentication)
throws AuthenticationException {
TestingAuthenticationToken token = createAuthenticationToken();
token.setDetails(resultDetails);
TestingAuthenticationToken request = createAuthenticationToken();
request.setDetails(details);
return token;
}
};
}
Authentication result = authMgr.authenticate(request);
assertEquals(details, result.getDetails());
private TestingAuthenticationToken createAuthenticationToken() {
return new TestingAuthenticationToken("name", "password", new GrantedAuthorityImpl[0]);
}
public void testDetailsAreNotSetOnAuthenticationTokenIfAlreadySetByProvider() {
@@ -60,23 +74,14 @@ public class AbstractAuthenticationManagerTests extends TestCase {
assertEquals(resultDetails, result.getDetails());
}
private TestingAuthenticationToken createAuthenticationToken() {
return new TestingAuthenticationToken("name","password", new GrantedAuthorityImpl[0]);
}
public void testDetailsAreSetOnAuthenticationTokenIfNotAlreadySetByProvider() {
AuthenticationManager authMgr = createAuthenticationManager(null);
Object details = new Object();
/**
* Creates an AuthenticationManager which will return a token with the given
* details object set on it.
*/
private AuthenticationManager createAuthenticationManager(final Object resultDetails) {
return new AbstractAuthenticationManager() {
protected Authentication doAuthentication(Authentication authentication)
throws AuthenticationException {
TestingAuthenticationToken token = createAuthenticationToken();
token.setDetails(resultDetails);
TestingAuthenticationToken request = createAuthenticationToken();
request.setDetails(details);
return token;
}
};
Authentication result = authMgr.authenticate(request);
assertEquals(details, result.getDetails());
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -27,7 +27,7 @@ import java.util.Locale;
* Tests {@link org.acegisecurity.AcegiMessageSource}.
*/
public class AcegiMessageSourceTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AcegiMessageSourceTests() {
super();
@@ -37,7 +37,7 @@ public class AcegiMessageSourceTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AcegiMessageSourceTests.class);
@@ -45,8 +45,7 @@ public class AcegiMessageSourceTests extends TestCase {
public void testOperation() {
AcegiMessageSource msgs = new AcegiMessageSource();
assertEquals("Proxy tickets are rejected",
msgs.getMessage("RejectProxyTickets.reject", null, Locale.ENGLISH));
assertEquals("Proxy tickets are rejected", msgs.getMessage("RejectProxyTickets.reject", null, Locale.ENGLISH));
}
public void testReplacableLookup() {
@@ -57,8 +56,8 @@ public class AcegiMessageSourceTests extends TestCase {
// Cause a message to be generated
MessageSourceAccessor messages = AcegiMessageSource.getAccessor();
assertEquals("Missing mandatory digest value; received header FOOBAR",
messages.getMessage("DigestProcessingFilter.missingMandatory",
new Object[] {"FOOBAR"}, "ERROR - FAILED TO LOOKUP"));
messages.getMessage("DigestProcessingFilter.missingMandatory", new Object[] {"FOOBAR"},
"ERROR - FAILED TO LOOKUP"));
// Revert to original Locale
LocaleContextHolder.setLocale(before);

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -29,7 +29,7 @@ import org.acegisecurity.providers.rememberme.RememberMeAuthenticationToken;
* @version $Id$
*/
public class AuthenticationTrustResolverImplTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AuthenticationTrustResolverImplTests() {
super();
@@ -39,7 +39,7 @@ public class AuthenticationTrustResolverImplTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AuthenticationTrustResolverImplTests.class);
@@ -68,13 +68,11 @@ public class AuthenticationTrustResolverImplTests extends TestCase {
public void testGettersSetters() {
AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl();
assertEquals(AnonymousAuthenticationToken.class,
trustResolver.getAnonymousClass());
assertEquals(AnonymousAuthenticationToken.class, trustResolver.getAnonymousClass());
trustResolver.setAnonymousClass(String.class);
assertEquals(String.class, trustResolver.getAnonymousClass());
assertEquals(RememberMeAuthenticationToken.class,
trustResolver.getRememberMeClass());
assertEquals(RememberMeAuthenticationToken.class, trustResolver.getRememberMeClass());
trustResolver.setRememberMeClass(String.class);
assertEquals(String.class, trustResolver.getRememberMeClass());
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -22,14 +22,13 @@ import java.util.Iterator;
/**
* Tests {@link ConfigAttributeEditor} and associated {@link
* ConfigAttributeDefinition}.
* Tests {@link ConfigAttributeEditor} and associated {@link ConfigAttributeDefinition}.
*
* @author Ben Alex
* @version $Id$
*/
public class ConfigAttributeEditorTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public ConfigAttributeEditorTests() {
super();
@@ -39,22 +38,21 @@ public class ConfigAttributeEditorTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(ConfigAttributeEditorTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testCorrectOperation() {
ConfigAttributeEditor editor = new ConfigAttributeEditor();
editor.setAsText("HELLO,DOCTOR,NAME,YESTERDAY,TOMORROW");
ConfigAttributeDefinition result = (ConfigAttributeDefinition) editor
.getValue();
ConfigAttributeDefinition result = (ConfigAttributeDefinition) editor.getValue();
Iterator iter = result.getConfigAttributes();
int position = 0;
@@ -76,8 +74,7 @@ public class ConfigAttributeEditorTests extends TestCase {
ConfigAttributeEditor editor = new ConfigAttributeEditor();
editor.setAsText("");
ConfigAttributeDefinition result = (ConfigAttributeDefinition) editor
.getValue();
ConfigAttributeDefinition result = (ConfigAttributeDefinition) editor.getValue();
assertTrue(result == null);
}
@@ -128,8 +125,7 @@ public class ConfigAttributeEditorTests extends TestCase {
ConfigAttributeEditor editor = new ConfigAttributeEditor();
editor.setAsText(null);
ConfigAttributeDefinition result = (ConfigAttributeDefinition) editor
.getValue();
ConfigAttributeDefinition result = (ConfigAttributeDefinition) editor.getValue();
assertTrue(result == null);
}
@@ -137,8 +133,7 @@ public class ConfigAttributeEditorTests extends TestCase {
ConfigAttributeEditor editor = new ConfigAttributeEditor();
editor.setAsText(" HELLO, DOCTOR,NAME, YESTERDAY ,TOMORROW ");
ConfigAttributeDefinition result = (ConfigAttributeDefinition) editor
.getValue();
ConfigAttributeDefinition result = (ConfigAttributeDefinition) editor.getValue();
Iterator iter = result.getConfigAttributes();
ArrayList list = new ArrayList();
@@ -158,8 +153,7 @@ public class ConfigAttributeEditorTests extends TestCase {
ConfigAttributeEditor editor = new ConfigAttributeEditor();
editor.setAsText("KOALA,KANGAROO,EMU,WOMBAT");
ConfigAttributeDefinition result = (ConfigAttributeDefinition) editor
.getValue();
ConfigAttributeDefinition result = (ConfigAttributeDefinition) editor.getValue();
assertEquals("[KOALA, KANGAROO, EMU, WOMBAT]", result.toString());
}
}

View File

@@ -25,7 +25,7 @@ import junit.framework.TestCase;
* @version $Id$
*/
public class GrantedAuthorityImplTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public GrantedAuthorityImplTests() {
super();
@@ -35,7 +35,7 @@ public class GrantedAuthorityImplTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(GrantedAuthorityImplTests.class);
@@ -62,8 +62,7 @@ public class GrantedAuthorityImplTests extends TestCase {
MockGrantedAuthorityImpl mock1 = new MockGrantedAuthorityImpl("TEST");
assertEquals(auth1, mock1);
MockGrantedAuthorityImpl mock2 = new MockGrantedAuthorityImpl(
"NOT_EQUAL");
MockGrantedAuthorityImpl mock2 = new MockGrantedAuthorityImpl("NOT_EQUAL");
assertTrue(!auth1.equals(mock2));
Integer int1 = new Integer(222);
@@ -75,7 +74,7 @@ public class GrantedAuthorityImplTests extends TestCase {
assertEquals("TEST", auth.toString());
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockGrantedAuthorityImpl implements GrantedAuthority {
private String role;

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -22,7 +22,7 @@ package org.acegisecurity;
* @version $Id$
*/
public interface ITargetObject {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public Integer computeHashCode(String input);

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -19,27 +19,25 @@ import java.util.Iterator;
/**
* Grants access if the user holds any of the authorities listed in the
* configuration attributes starting with "MOCK_".
* Grants access if the user holds any of the authorities listed in the configuration attributes starting with
* "MOCK_".
*
* @author Ben Alex
* @version $Id$
*/
public class MockAccessDecisionManager implements AccessDecisionManager {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public void decide(Authentication authentication, Object object,
ConfigAttributeDefinition config) throws AccessDeniedException {
public void decide(Authentication authentication, Object object, ConfigAttributeDefinition config)
throws AccessDeniedException {
Iterator iter = config.getConfigAttributes();
while (iter.hasNext()) {
ConfigAttribute attr = (ConfigAttribute) iter.next();
if (this.supports(attr)) {
for (int i = 0; i < authentication.getAuthorities().length;
i++) {
if (attr.getAttribute().equals(authentication
.getAuthorities()[i].getAuthority())) {
for (int i = 0; i < authentication.getAuthorities().length; i++) {
if (attr.getAttribute().equals(authentication.getAuthorities()[i].getAuthority())) {
return;
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -20,21 +20,20 @@ import org.acegisecurity.acl.AclManager;
/**
* Returns the indicated collection of <code>AclEntry</code>s when the given
* <code>Authentication</code> principal is presented for the indicated domain
* <code>Object</code> instance.
* Returns the indicated collection of <code>AclEntry</code>s when the given <code>Authentication</code> principal
* is presented for the indicated domain <code>Object</code> instance.
*
* @author Ben Alex
* @version $Id$
*/
public class MockAclManager implements AclManager {
//~ Instance fields ========================================================
//~ Instance fields ================================================================================================
private Object object;
private Object principal;
private AclEntry[] acls;
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public MockAclManager(Object domainObject, Object principal, AclEntry[] acls) {
this.object = domainObject;
@@ -44,12 +43,10 @@ public class MockAclManager implements AclManager {
private MockAclManager() {}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public AclEntry[] getAcls(Object domainInstance,
Authentication authentication) {
if (domainInstance.equals(object)
&& authentication.getPrincipal().equals(principal)) {
public AclEntry[] getAcls(Object domainInstance, Authentication authentication) {
if (domainInstance.equals(object) && authentication.getPrincipal().equals(principal)) {
return acls;
} else {
return null;

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -19,18 +19,16 @@ import java.util.Iterator;
/**
* If there is a configuration attribute of "AFTER_INVOCATION_MOCK", modifies
* the return value to null.
* If there is a configuration attribute of "AFTER_INVOCATION_MOCK", modifies the return value to null.
*
* @author Ben Alex
* @version $Id$
*/
public class MockAfterInvocationManager implements AfterInvocationManager {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public Object decide(Authentication authentication, Object object,
ConfigAttributeDefinition config, Object returnedObject)
throws AccessDeniedException {
public Object decide(Authentication authentication, Object object, ConfigAttributeDefinition config,
Object returnedObject) throws AccessDeniedException {
Iterator iter = config.getConfigAttributes();
while (iter.hasNext()) {

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -20,17 +20,15 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Simply returns an <code>ApplicationContext</code> which has a couple of
* <code>ApplicationEvent</code> listeners.
* Simply returns an <code>ApplicationContext</code> which has a couple of <code>ApplicationEvent</code> listeners.
*
* @author Ben Alex
* @version $Id$
*/
public class MockApplicationContext {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static ConfigurableApplicationContext getContext() {
return new ClassPathXmlApplicationContext(
"org/acegisecurity/applicationContext.xml");
return new ClassPathXmlApplicationContext("org/acegisecurity/applicationContext.xml");
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -33,11 +33,11 @@ import javax.servlet.http.HttpServletResponse;
* @version $Id$
*/
public class MockAuthenticationEntryPoint implements AuthenticationEntryPoint {
//~ Instance fields ========================================================
//~ Instance fields ================================================================================================
private String url;
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public MockAuthenticationEntryPoint(String url) {
this.url = url;
@@ -47,12 +47,11 @@ public class MockAuthenticationEntryPoint implements AuthenticationEntryPoint {
super();
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public void commence(ServletRequest request, ServletResponse response,
AuthenticationException authenticationException)
throws IOException, ServletException {
((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request)
.getContextPath() + url);
((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + url);
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -30,7 +30,7 @@ import javax.servlet.ServletResponse;
* @version $Id$
*/
public class MockFilterChain implements FilterChain {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public void doFilter(ServletRequest arg0, ServletResponse arg1)
throws IOException, ServletException {

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -30,11 +30,11 @@ import javax.servlet.ServletContext;
* @version $Id$
*/
public class MockFilterConfig implements FilterConfig {
//~ Instance fields ========================================================
//~ Instance fields ================================================================================================
private Map map = new HashMap();
//~ Methods ================================================================
//~ Methods ========================================================================================================
public String getFilterName() {
throw new UnsupportedOperationException("mock method not implemented");
@@ -54,11 +54,11 @@ public class MockFilterConfig implements FilterConfig {
throw new UnsupportedOperationException("mock method not implemented");
}
public void setInitParmeter(String parameter, String value) {
map.put(parameter, value);
}
public ServletContext getServletContext() {
throw new UnsupportedOperationException("mock method not implemented");
}
public void setInitParmeter(String parameter, String value) {
map.put(parameter, value);
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -30,12 +30,12 @@ import java.lang.reflect.Method;
* @version $Id$
*/
public class MockJoinPoint implements JoinPoint {
//~ Instance fields ========================================================
//~ Instance fields ================================================================================================
private Method beingInvoked;
private Object object;
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public MockJoinPoint(Object object, Method beingInvoked) {
this.object = object;
@@ -44,7 +44,7 @@ public class MockJoinPoint implements JoinPoint {
private MockJoinPoint() {}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public Object[] getArgs() {
throw new UnsupportedOperationException("mock not implemented");
@@ -82,7 +82,7 @@ public class MockJoinPoint implements JoinPoint {
throw new UnsupportedOperationException("mock not implemented");
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockCodeSignature implements CodeSignature {
private Method beingInvoked;

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -27,12 +27,12 @@ import javax.servlet.ServletRequest;
* @version $Id$
*/
public class MockPortResolver implements PortResolver {
//~ Instance fields ========================================================
//~ Instance fields ================================================================================================
private int http = 80;
private int https = 443;
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public MockPortResolver(int http, int https) {
this.http = http;
@@ -41,11 +41,10 @@ public class MockPortResolver implements PortResolver {
private MockPortResolver() {}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public int getServerPort(ServletRequest request) {
if ((request.getScheme() != null)
&& request.getScheme().equals("https")) {
if ((request.getScheme() != null) && request.getScheme().equals("https")) {
return https;
} else {
return http;

View File

@@ -19,20 +19,20 @@ import org.acegisecurity.providers.AbstractAuthenticationToken;
/**
* Simple holder that indicates the {@link MockRunAsManager} returned a
* different <Code>Authentication</code> object.
* Simple holder that indicates the {@link MockRunAsManager} returned a different <Code>Authentication</code>
* object.
*
* @author Ben Alex
* @version $Id$
*/
public class MockRunAsAuthenticationToken extends AbstractAuthenticationToken {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public MockRunAsAuthenticationToken() {
super(null);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public Object getCredentials() {
return null;

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -19,17 +19,16 @@ import java.util.Iterator;
/**
* Returns a new run-as identity if configuration attribute RUN_AS is found.
* The new identity is simply an empty {@link MockRunAsAuthenticationToken}.
* Returns a new run-as identity if configuration attribute RUN_AS is found. The new identity is simply an empty
* {@link MockRunAsAuthenticationToken}.
*
* @author Ben Alex
* @version $Id$
*/
public class MockRunAsManager implements RunAsManager {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public Authentication buildRunAs(Authentication authentication,
Object object, ConfigAttributeDefinition config) {
public Authentication buildRunAs(Authentication authentication, Object object, ConfigAttributeDefinition config) {
Iterator iter = config.getConfigAttributes();
while (iter.hasNext()) {

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -16,27 +16,18 @@
package org.acegisecurity;
/**
* Simply extends {@link TargetObject} so we have a different object to put
* configuration attributes against.
*
* <P>
* There is no different behaviour. We have to define each method so that
* <code>Class.getMethod(methodName, args)</code> returns a
* <code>Method</code> referencing this class rather than the parent class.
* </p>
*
* <P>
* We need to implement <code>ITargetObject</code> again because the
* <code>MethodDefinitionAttributes</code> only locates attributes on
* interfaces explicitly defined by the intercepted class (not the interfaces
* defined by its parent class or classes).
* </p>
* Simply extends {@link TargetObject} so we have a different object to put configuration attributes against.<P>There
* is no different behaviour. We have to define each method so that <code>Class.getMethod(methodName, args)</code>
* returns a <code>Method</code> referencing this class rather than the parent class.</p>
* <P>We need to implement <code>ITargetObject</code> again because the <code>MethodDefinitionAttributes</code>
* only locates attributes on interfaces explicitly defined by the intercepted class (not the interfaces defined by
* its parent class or classes).</p>
*
* @author Ben Alex
* @version $Id$
*/
public class OtherTargetObject extends TargetObject implements ITargetObject {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public int countLength(String input) {
return super.countLength(input);

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -22,22 +22,21 @@ import javax.sql.DataSource;
/**
* Singleton which provides a populated database connection for all
* JDBC-related unit tests.
* Singleton which provides a populated database connection for all JDBC-related unit tests.
*
* @author Ben Alex
* @version $Id$
*/
public class PopulatedDatabase {
//~ Static fields/initializers =============================================
//~ Static fields/initializers =====================================================================================
private static DriverManagerDataSource dataSource = null;
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
private PopulatedDatabase() {}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static DataSource getDataSource() {
if (dataSource == null) {
@@ -60,8 +59,7 @@ public class PopulatedDatabase {
"CREATE TABLE USERS(USERNAME VARCHAR_IGNORECASE(50) NOT NULL PRIMARY KEY,PASSWORD VARCHAR_IGNORECASE(50) NOT NULL,ENABLED BOOLEAN NOT NULL)");
template.execute(
"CREATE TABLE AUTHORITIES(USERNAME VARCHAR_IGNORECASE(50) NOT NULL,AUTHORITY VARCHAR_IGNORECASE(50) NOT NULL,CONSTRAINT FK_AUTHORITIES_USERS FOREIGN KEY(USERNAME) REFERENCES USERS(USERNAME))");
template.execute(
"CREATE UNIQUE INDEX IX_AUTH_USERNAME ON AUTHORITIES(USERNAME,AUTHORITY)");
template.execute("CREATE UNIQUE INDEX IX_AUTH_USERNAME ON AUTHORITIES(USERNAME,AUTHORITY)");
template.execute(
"CREATE TABLE ACL_OBJECT_IDENTITY(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,OBJECT_IDENTITY VARCHAR_IGNORECASE(250) NOT NULL,PARENT_OBJECT BIGINT,ACL_CLASS VARCHAR_IGNORECASE(250) NOT NULL,CONSTRAINT UNIQUE_OBJECT_IDENTITY UNIQUE(OBJECT_IDENTITY),CONSTRAINT SYS_FK_3 FOREIGN KEY(PARENT_OBJECT) REFERENCES ACL_OBJECT_IDENTITY(ID))");
template.execute(
@@ -72,16 +70,11 @@ public class PopulatedDatabase {
template.execute("INSERT INTO USERS VALUES('peter','opal',FALSE)");
template.execute("INSERT INTO USERS VALUES('scott','wombat',TRUE)");
template.execute("INSERT INTO USERS VALUES('cooper','kookaburra',TRUE)");
template.execute(
"INSERT INTO AUTHORITIES VALUES('marissa','ROLE_TELLER')");
template.execute(
"INSERT INTO AUTHORITIES VALUES('marissa','ROLE_SUPERVISOR')");
template.execute(
"INSERT INTO AUTHORITIES VALUES('dianne','ROLE_TELLER')");
template.execute(
"INSERT INTO AUTHORITIES VALUES('scott','ROLE_TELLER')");
template.execute(
"INSERT INTO AUTHORITIES VALUES('peter','ROLE_TELLER')");
template.execute("INSERT INTO AUTHORITIES VALUES('marissa','ROLE_TELLER')");
template.execute("INSERT INTO AUTHORITIES VALUES('marissa','ROLE_SUPERVISOR')");
template.execute("INSERT INTO AUTHORITIES VALUES('dianne','ROLE_TELLER')");
template.execute("INSERT INTO AUTHORITIES VALUES('scott','ROLE_TELLER')");
template.execute("INSERT INTO AUTHORITIES VALUES('peter','ROLE_TELLER')");
template.execute(
"INSERT INTO acl_object_identity VALUES (1, 'org.acegisecurity.acl.DomainObject:1', null, 'org.acegisecurity.acl.basic.SimpleAclEntry');");
template.execute(
@@ -100,15 +93,10 @@ public class PopulatedDatabase {
"INSERT INTO acl_object_identity VALUES (7, 'org.acegisecurity.acl.DomainObject:7', 3, 'some.invalid.acl.entry.class');");
// ----- FINISH deviation from normal sample data load script -----
template.execute(
"INSERT INTO acl_permission VALUES (null, 1, 'ROLE_SUPERVISOR', 1);");
template.execute(
"INSERT INTO acl_permission VALUES (null, 2, 'ROLE_SUPERVISOR', 0);");
template.execute(
"INSERT INTO acl_permission VALUES (null, 2, 'marissa', 2);");
template.execute(
"INSERT INTO acl_permission VALUES (null, 3, 'scott', 14);");
template.execute(
"INSERT INTO acl_permission VALUES (null, 6, 'scott', 1);");
template.execute("INSERT INTO acl_permission VALUES (null, 1, 'ROLE_SUPERVISOR', 1);");
template.execute("INSERT INTO acl_permission VALUES (null, 2, 'ROLE_SUPERVISOR', 0);");
template.execute("INSERT INTO acl_permission VALUES (null, 2, 'marissa', 2);");
template.execute("INSERT INTO acl_permission VALUES (null, 3, 'scott', 14);");
template.execute("INSERT INTO acl_permission VALUES (null, 6, 'scott', 1);");
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -25,7 +25,7 @@ import junit.framework.TestCase;
* @version $Id$
*/
public class SecurityConfigTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public SecurityConfigTests() {
super();
@@ -35,26 +35,26 @@ public class SecurityConfigTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(SecurityConfigTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testHashCode() {
SecurityConfig config = new SecurityConfig("TEST");
assertEquals("TEST".hashCode(), config.hashCode());
}
public void testNoArgConstructorDoesntExist() {
Class clazz = SecurityConfig.class;
try {
clazz.getDeclaredConstructor((Class[])null);
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
} catch (NoSuchMethodException expected) {
assertTrue(true);
@@ -90,7 +90,7 @@ public class SecurityConfigTests extends TestCase {
assertEquals("TEST", config.toString());
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockConfigAttribute implements ConfigAttribute {
private String attribute;

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -25,7 +25,7 @@ import org.acegisecurity.context.SecurityContextHolder;
* @version $Id$
*/
public class TargetObject implements ITargetObject {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public Integer computeHashCode(String input) {
return new Integer(input.hashCode());
@@ -36,45 +36,37 @@ public class TargetObject implements ITargetObject {
}
/**
* Returns the lowercase string, followed by security environment
* information.
* Returns the lowercase string, followed by security environment information.
*
* @param input the message to make lowercase
*
* @return the lowercase message, a space, the <code>Authentication</code>
* class that was on the <code>SecurityContext</code> at the time
* of method invocation, and a boolean indicating if the
* @return the lowercase message, a space, the <code>Authentication</code> class that was on the
* <code>SecurityContext</code> at the time of method invocation, and a boolean indicating if the
* <code>Authentication</code> object is authenticated or not
*/
public String makeLowerCase(String input) {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null) {
return input.toLowerCase() + " Authentication empty";
} else {
return input.toLowerCase() + " " + auth.getClass().getName() + " "
+ auth.isAuthenticated();
return input.toLowerCase() + " " + auth.getClass().getName() + " " + auth.isAuthenticated();
}
}
/**
* Returns the uppercase string, followed by security environment
* information.
* Returns the uppercase string, followed by security environment information.
*
* @param input the message to make uppercase
*
* @return the uppercase message, a space, the <code>Authentication</code>
* class that was on the <code>SecurityContext</code> at the time
* of method invocation, and a boolean indicating if the
* @return the uppercase message, a space, the <code>Authentication</code> class that was on the
* <code>SecurityContext</code> at the time of method invocation, and a boolean indicating if the
* <code>Authentication</code> object is authenticated or not
*/
public String makeUpperCase(String input) {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return input.toUpperCase() + " " + auth.getClass().getName() + " "
+ auth.isAuthenticated();
return input.toUpperCase() + " " + auth.getClass().getName() + " " + auth.isAuthenticated();
}
/**
@@ -82,6 +74,7 @@ public class TargetObject implements ITargetObject {
*
* @param input the message to be made lower-case
*
* @return DOCUMENT ME!
*/
public String publicMakeLowerCase(String input) {
return this.makeLowerCase(input);

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -20,8 +20,10 @@ import junit.framework.TestCase;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.acl.basic.NamedEntityObjectIdentity;
import org.acegisecurity.acl.basic.SimpleAclEntry;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import java.util.List;
@@ -35,7 +37,7 @@ import java.util.Vector;
* @version $Id$
*/
public class AclProviderManagerTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AclProviderManagerTests() {
super();
@@ -45,16 +47,27 @@ public class AclProviderManagerTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AclProviderManagerTests.class);
}
private AclProviderManager makeProviderManager() {
MockProvider provider1 = new MockProvider();
List providers = new Vector();
providers.add(provider1);
AclProviderManager mgr = new AclProviderManager();
mgr.setProviders(providers);
return mgr;
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAclLookupFails() {
AclProviderManager mgr = makeProviderManager();
assertNull(mgr.getAcls(new Integer(5)));
@@ -62,8 +75,7 @@ public class AclProviderManagerTests extends TestCase {
public void testAclLookupForGivenAuthenticationSuccess() {
AclProviderManager mgr = makeProviderManager();
assertNotNull(mgr.getAcls("STRING",
new UsernamePasswordAuthenticationToken("marissa", "not used")));
assertNotNull(mgr.getAcls("STRING", new UsernamePasswordAuthenticationToken("marissa", "not used")));
}
public void testAclLookupSuccess() {
@@ -82,8 +94,7 @@ public class AclProviderManagerTests extends TestCase {
}
try {
mgr.getAcls(null,
new UsernamePasswordAuthenticationToken("marissa", "not used"));
mgr.getAcls(null, new UsernamePasswordAuthenticationToken("marissa", "not used"));
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
@@ -99,8 +110,7 @@ public class AclProviderManagerTests extends TestCase {
public void testReturnsNullIfNoSupportingProvider() {
AclProviderManager mgr = makeProviderManager();
assertNull(mgr.getAcls(new Integer(4),
new UsernamePasswordAuthenticationToken("marissa", "not used")));
assertNull(mgr.getAcls(new Integer(4), new UsernamePasswordAuthenticationToken("marissa", "not used")));
assertNull(mgr.getAcls(new Integer(4)));
}
@@ -149,35 +159,21 @@ public class AclProviderManagerTests extends TestCase {
assertEquals(1, mgr.getProviders().size());
}
private AclProviderManager makeProviderManager() {
MockProvider provider1 = new MockProvider();
List providers = new Vector();
providers.add(provider1);
AclProviderManager mgr = new AclProviderManager();
mgr.setProviders(providers);
return mgr;
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockProvider implements AclProvider {
private UsernamePasswordAuthenticationToken marissa = new UsernamePasswordAuthenticationToken("marissa",
"not used",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_FOO"), new GrantedAuthorityImpl("ROLE_BAR")});
private SimpleAclEntry entry100Marissa = new SimpleAclEntry(marissa
.getPrincipal(),
private SimpleAclEntry entry100Marissa = new SimpleAclEntry(marissa.getPrincipal(),
new NamedEntityObjectIdentity("OBJECT", "100"), null, 2);
private UsernamePasswordAuthenticationToken scott = new UsernamePasswordAuthenticationToken("scott",
"not used",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_FOO"), new GrantedAuthorityImpl("ROLE_MANAGER")});
private SimpleAclEntry entry100Scott = new SimpleAclEntry(scott
.getPrincipal(),
private SimpleAclEntry entry100Scott = new SimpleAclEntry(scott.getPrincipal(),
new NamedEntityObjectIdentity("OBJECT", "100"), null, 4);
public AclEntry[] getAcls(Object domainInstance,
Authentication authentication) {
public AclEntry[] getAcls(Object domainInstance, Authentication authentication) {
if (authentication.getPrincipal().equals(scott.getPrincipal())) {
return new AclEntry[] {entry100Scott};
}

View File

@@ -38,11 +38,11 @@ import java.util.Map;
* @version $Id$
*/
public class BasicAclProviderTests extends TestCase {
//~ Static fields/initializers =============================================
//~ Static fields/initializers =====================================================================================
public static final String OBJECT_IDENTITY = "org.acegisecurity.acl.DomainObject";
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public BasicAclProviderTests() {
super();
@@ -52,7 +52,7 @@ public class BasicAclProviderTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(BasicAclProviderTests.class);
@@ -175,16 +175,14 @@ public class BasicAclProviderTests extends TestCase {
assertEquals(14, ((BasicAclEntry) acls[0]).getMask());
assertEquals("ROLE_SUPERVISOR", ((BasicAclEntry) acls[1]).getRecipient());
assertEquals(1, ((BasicAclEntry) acls[1]).getMask());
assertEquals(JdbcDaoImpl.RECIPIENT_USED_FOR_INHERITENCE_MARKER,
((BasicAclEntry) acls[2]).getRecipient());
assertEquals(JdbcDaoImpl.RECIPIENT_USED_FOR_INHERITENCE_MARKER, ((BasicAclEntry) acls[2]).getRecipient());
}
public void testGetAclsWithAuthentication() throws Exception {
BasicAclProvider provider = new BasicAclProvider();
provider.setBasicAclDao(makePopulatedJdbcDao());
Authentication scott = new UsernamePasswordAuthenticationToken("scott",
"unused");
Authentication scott = new UsernamePasswordAuthenticationToken("scott", "unused");
Object object = new MockDomain(6);
AclEntry[] acls = provider.getAcls(object, scott);
@@ -195,12 +193,9 @@ public class BasicAclProviderTests extends TestCase {
public void testGettersSetters() {
BasicAclProvider provider = new BasicAclProvider();
assertEquals(NullAclEntryCache.class,
provider.getBasicAclEntryCache().getClass());
assertEquals(NamedEntityObjectIdentity.class,
provider.getDefaultAclObjectIdentityClass());
assertEquals(GrantedAuthorityEffectiveAclsResolver.class,
provider.getEffectiveAclsResolver().getClass());
assertEquals(NullAclEntryCache.class, provider.getBasicAclEntryCache().getClass());
assertEquals(NamedEntityObjectIdentity.class, provider.getDefaultAclObjectIdentityClass());
assertEquals(GrantedAuthorityEffectiveAclsResolver.class, provider.getEffectiveAclsResolver().getClass());
provider.setBasicAclEntryCache(null);
assertNull(provider.getBasicAclEntryCache());
@@ -326,7 +321,7 @@ public class BasicAclProviderTests extends TestCase {
assertFalse(provider.supports(new Integer(34)));
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockCache implements BasicAclEntryCache {
private Map map = new HashMap();
@@ -338,8 +333,7 @@ public class BasicAclProviderTests extends TestCase {
return map;
}
public BasicAclEntry[] getEntriesFromCache(
AclObjectIdentity aclObjectIdentity) {
public BasicAclEntry[] getEntriesFromCache(AclObjectIdentity aclObjectIdentity) {
gets++;
Object result = map.get(aclObjectIdentity);
@@ -391,8 +385,7 @@ public class BasicAclProviderTests extends TestCase {
}
public AclObjectIdentity getAclObjectIdentity() {
return new NamedEntityObjectIdentity(OBJECT_IDENTITY,
new Integer(id).toString());
return new NamedEntityObjectIdentity(OBJECT_IDENTITY, new Integer(id).toString());
}
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -19,8 +19,11 @@ import junit.framework.TestCase;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.acl.AclEntry;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.userdetails.User;
@@ -31,7 +34,7 @@ import org.acegisecurity.userdetails.User;
* @version $Id$
*/
public class GrantedAuthorityEffectiveAclsResolverTests extends TestCase {
//~ Instance fields ========================================================
//~ Instance fields ================================================================================================
private SimpleAclEntry entry100RoleEverybody = new SimpleAclEntry("ROLE_EVERYBODY",
new NamedEntityObjectIdentity("OBJECT", "100"), null, 14);
@@ -39,31 +42,27 @@ public class GrantedAuthorityEffectiveAclsResolverTests extends TestCase {
new NamedEntityObjectIdentity("OBJECT", "100"), null, 0);
private SimpleAclEntry entry100RoleTwo = new SimpleAclEntry("ROLE_TWO",
new NamedEntityObjectIdentity("OBJECT", "100"), null, 2);
private UsernamePasswordAuthenticationToken scott = new UsernamePasswordAuthenticationToken("scott",
"not used",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_EVERYBODY"), new GrantedAuthorityImpl(
"ROLE_TWO")});
private SimpleAclEntry entry100Scott = new SimpleAclEntry(scott
.getPrincipal(), new NamedEntityObjectIdentity("OBJECT", "100"),
null, 4);
private UsernamePasswordAuthenticationToken dianne = new UsernamePasswordAuthenticationToken("dianne",
"not used");
private UsernamePasswordAuthenticationToken scott = new UsernamePasswordAuthenticationToken("scott", "not used",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_EVERYBODY"), new GrantedAuthorityImpl("ROLE_TWO")});
private SimpleAclEntry entry100Scott = new SimpleAclEntry(scott.getPrincipal(),
new NamedEntityObjectIdentity("OBJECT", "100"), null, 4);
private UsernamePasswordAuthenticationToken dianne = new UsernamePasswordAuthenticationToken("dianne", "not used");
private UsernamePasswordAuthenticationToken marissa = new UsernamePasswordAuthenticationToken("marissa",
"not used",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_EVERYBODY"), new GrantedAuthorityImpl("ROLE_ONE")});
private SimpleAclEntry entry100Marissa = new SimpleAclEntry(marissa
.getPrincipal(), new NamedEntityObjectIdentity("OBJECT", "100"),
null, 2);
private SimpleAclEntry entry100Marissa = new SimpleAclEntry(marissa.getPrincipal(),
new NamedEntityObjectIdentity("OBJECT", "100"), null, 2);
private UsernamePasswordAuthenticationToken scottWithUserDetails = new UsernamePasswordAuthenticationToken(new User(
"scott", "NOT_USED", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl(
"ROLE_EVERYBODY")}), "not used",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_EVERYBODY")}), "not used",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_EVERYBODY"), new GrantedAuthorityImpl("ROLE_TWO")});
// convenience group
private SimpleAclEntry[] acls = {entry100Marissa, entry100Scott, entry100RoleEverybody, entry100RoleOne, entry100RoleTwo};
private SimpleAclEntry[] acls = {
entry100Marissa, entry100Scott, entry100RoleEverybody, entry100RoleOne, entry100RoleTwo
};
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public GrantedAuthorityEffectiveAclsResolverTests() {
super();
@@ -73,16 +72,16 @@ public class GrantedAuthorityEffectiveAclsResolverTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(GrantedAuthorityEffectiveAclsResolverTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testResolveAclsForDianneWhoHasANullForAuthorities() {
GrantedAuthorityEffectiveAclsResolver resolver = new GrantedAuthorityEffectiveAclsResolver();
assertNull(resolver.resolveEffectiveAcls(acls, dianne));
@@ -91,35 +90,25 @@ public class GrantedAuthorityEffectiveAclsResolverTests extends TestCase {
public void testResolveAclsForMarissa() {
GrantedAuthorityEffectiveAclsResolver resolver = new GrantedAuthorityEffectiveAclsResolver();
assertEquals(3, resolver.resolveEffectiveAcls(acls, marissa).length);
assertEquals(entry100Marissa,
resolver.resolveEffectiveAcls(acls, marissa)[0]);
assertEquals(entry100RoleEverybody,
resolver.resolveEffectiveAcls(acls, marissa)[1]);
assertEquals(entry100RoleOne,
resolver.resolveEffectiveAcls(acls, marissa)[2]);
assertEquals(entry100Marissa, resolver.resolveEffectiveAcls(acls, marissa)[0]);
assertEquals(entry100RoleEverybody, resolver.resolveEffectiveAcls(acls, marissa)[1]);
assertEquals(entry100RoleOne, resolver.resolveEffectiveAcls(acls, marissa)[2]);
}
public void testResolveAclsForScottWithStringObjectAsPrincipal() {
GrantedAuthorityEffectiveAclsResolver resolver = new GrantedAuthorityEffectiveAclsResolver();
assertEquals(3, resolver.resolveEffectiveAcls(acls, scott).length);
assertEquals(entry100Scott,
resolver.resolveEffectiveAcls(acls, scott)[0]);
assertEquals(entry100RoleEverybody,
resolver.resolveEffectiveAcls(acls, scott)[1]);
assertEquals(entry100RoleTwo,
resolver.resolveEffectiveAcls(acls, scott)[2]);
assertEquals(entry100Scott, resolver.resolveEffectiveAcls(acls, scott)[0]);
assertEquals(entry100RoleEverybody, resolver.resolveEffectiveAcls(acls, scott)[1]);
assertEquals(entry100RoleTwo, resolver.resolveEffectiveAcls(acls, scott)[2]);
}
public void testResolveAclsForScottWithUserDetailsObjectAsPrincipal() {
GrantedAuthorityEffectiveAclsResolver resolver = new GrantedAuthorityEffectiveAclsResolver();
assertEquals(3,
resolver.resolveEffectiveAcls(acls, scottWithUserDetails).length);
assertEquals(entry100Scott,
resolver.resolveEffectiveAcls(acls, scottWithUserDetails)[0]);
assertEquals(entry100RoleEverybody,
resolver.resolveEffectiveAcls(acls, scottWithUserDetails)[1]);
assertEquals(entry100RoleTwo,
resolver.resolveEffectiveAcls(acls, scottWithUserDetails)[2]);
assertEquals(3, resolver.resolveEffectiveAcls(acls, scottWithUserDetails).length);
assertEquals(entry100Scott, resolver.resolveEffectiveAcls(acls, scottWithUserDetails)[0]);
assertEquals(entry100RoleEverybody, resolver.resolveEffectiveAcls(acls, scottWithUserDetails)[1]);
assertEquals(entry100RoleTwo, resolver.resolveEffectiveAcls(acls, scottWithUserDetails)[2]);
}
public void testResolveAclsReturnsNullIfNoAclsInFirstPlace() {
@@ -129,11 +118,13 @@ public class GrantedAuthorityEffectiveAclsResolverTests extends TestCase {
public void testSkipsNonBasicAclEntryObjects() {
GrantedAuthorityEffectiveAclsResolver resolver = new GrantedAuthorityEffectiveAclsResolver();
AclEntry[] basicAcls = {entry100Marissa, entry100Scott, entry100RoleEverybody, entry100RoleOne, new MockAcl(), entry100RoleTwo};
AclEntry[] basicAcls = {
entry100Marissa, entry100Scott, entry100RoleEverybody, entry100RoleOne, new MockAcl(), entry100RoleTwo
};
assertEquals(3, resolver.resolveEffectiveAcls(basicAcls, marissa).length);
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockAcl implements AclEntry {
// does nothing

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -16,9 +16,8 @@
package org.acegisecurity.acl.basic;
/**
* Implements <code>AclObjectIdentity</code> but is incompatible with
* <code>BasicAclProvider</code> because it cannot be constructed by passing
* in a domain object instance.
* Implements <code>AclObjectIdentity</code> but is incompatible with <code>BasicAclProvider</code> because it
* cannot be constructed by passing in a domain object instance.
*
* @author Ben Alex
* @version $Id$

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -25,7 +25,7 @@ import junit.framework.TestCase;
* @version $Id$
*/
public class NamedEntityObjectIdentityTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public NamedEntityObjectIdentityTests() {
super();
@@ -35,16 +35,16 @@ public class NamedEntityObjectIdentityTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(NamedEntityObjectIdentityTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testConstructionViaReflection() throws Exception {
SomeDomain domainObject = new SomeDomain();
domainObject.setId(34);
@@ -75,28 +75,26 @@ public class NamedEntityObjectIdentityTests extends TestCase {
}
}
public void testEquality() {
NamedEntityObjectIdentity original = new NamedEntityObjectIdentity("foo", "12");
assertFalse(original.equals(null));
assertFalse(original.equals(new Integer(354)));
assertFalse(original.equals(new NamedEntityObjectIdentity("foo", "23232")));
assertTrue(original.equals(new NamedEntityObjectIdentity("foo", "12")));
assertTrue(original.equals(original));
}
public void testNoArgConstructorDoesntExist() {
Class clazz = NamedEntityObjectIdentity.class;
try {
clazz.getDeclaredConstructor((Class[])null);
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
} catch (NoSuchMethodException expected) {
assertTrue(true);
}
}
public void testEquality() {
NamedEntityObjectIdentity original = new NamedEntityObjectIdentity("foo",
"12");
assertFalse(original.equals(null));
assertFalse(original.equals(new Integer(354)));
assertFalse(original.equals(
new NamedEntityObjectIdentity("foo", "23232")));
assertTrue(original.equals(new NamedEntityObjectIdentity("foo", "12")));
assertTrue(original.equals(original));
}
public void testNormalConstructionRejectedIfInvalidArguments()
throws Exception {
try {
@@ -129,8 +127,7 @@ public class NamedEntityObjectIdentityTests extends TestCase {
}
public void testNormalOperation() {
NamedEntityObjectIdentity name = new NamedEntityObjectIdentity("domain",
"id");
NamedEntityObjectIdentity name = new NamedEntityObjectIdentity("domain", "id");
assertEquals("domain", name.getClassname());
assertEquals("id", name.getId());
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -25,7 +25,7 @@ import junit.framework.TestCase;
* @version $Id$
*/
public class SimpleAclEntryTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public SimpleAclEntryTests() {
super();
@@ -35,22 +35,20 @@ public class SimpleAclEntryTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(SimpleAclEntryTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testCorrectOperation() {
String recipient = "marissa";
AclObjectIdentity objectIdentity = new NamedEntityObjectIdentity("domain",
"12");
SimpleAclEntry acl = new SimpleAclEntry(recipient, objectIdentity,
null, 0);
AclObjectIdentity objectIdentity = new NamedEntityObjectIdentity("domain", "12");
SimpleAclEntry acl = new SimpleAclEntry(recipient, objectIdentity, null, 0);
assertFalse(acl.isPermitted(SimpleAclEntry.ADMINISTRATION));
acl.addPermission(SimpleAclEntry.ADMINISTRATION);
@@ -90,8 +88,7 @@ public class SimpleAclEntryTests extends TestCase {
public void testDetectsNullOnMainConstructor() {
String recipient = "marissa";
AclObjectIdentity objectIdentity = new NamedEntityObjectIdentity("domain",
"12");
AclObjectIdentity objectIdentity = new NamedEntityObjectIdentity("domain", "12");
try {
new SimpleAclEntry(recipient, null, null, 2);
@@ -111,13 +108,11 @@ public class SimpleAclEntryTests extends TestCase {
public void testGettersSetters() {
SimpleAclEntry acl = new SimpleAclEntry();
AclObjectIdentity objectIdentity = new NamedEntityObjectIdentity("domain",
"693");
AclObjectIdentity objectIdentity = new NamedEntityObjectIdentity("domain", "693");
acl.setAclObjectIdentity(objectIdentity);
assertEquals(objectIdentity, acl.getAclObjectIdentity());
AclObjectIdentity parentObjectIdentity = new NamedEntityObjectIdentity("domain",
"13");
AclObjectIdentity parentObjectIdentity = new NamedEntityObjectIdentity("domain", "13");
acl.setAclObjectParentIdentity(parentObjectIdentity);
assertEquals(parentObjectIdentity, acl.getAclObjectParentIdentity());
@@ -130,10 +125,8 @@ public class SimpleAclEntryTests extends TestCase {
public void testRejectsInvalidMasksInAddMethod() {
String recipient = "marissa";
AclObjectIdentity objectIdentity = new NamedEntityObjectIdentity("domain",
"12");
SimpleAclEntry acl = new SimpleAclEntry(recipient, objectIdentity,
null, 4);
AclObjectIdentity objectIdentity = new NamedEntityObjectIdentity("domain", "12");
SimpleAclEntry acl = new SimpleAclEntry(recipient, objectIdentity, null, 4);
try {
acl.addPermission(Integer.MAX_VALUE);
@@ -145,10 +138,8 @@ public class SimpleAclEntryTests extends TestCase {
public void testRejectsInvalidMasksInDeleteMethod() {
String recipient = "marissa";
AclObjectIdentity objectIdentity = new NamedEntityObjectIdentity("domain",
"12");
SimpleAclEntry acl = new SimpleAclEntry(recipient, objectIdentity,
null, 0);
AclObjectIdentity objectIdentity = new NamedEntityObjectIdentity("domain", "12");
SimpleAclEntry acl = new SimpleAclEntry(recipient, objectIdentity, null, 0);
acl.addPermissions(new int[] {SimpleAclEntry.READ, SimpleAclEntry.WRITE, SimpleAclEntry.CREATE});
try {
@@ -161,10 +152,8 @@ public class SimpleAclEntryTests extends TestCase {
public void testRejectsInvalidMasksInTogglePermissionMethod() {
String recipient = "marissa";
AclObjectIdentity objectIdentity = new NamedEntityObjectIdentity("domain",
"12");
SimpleAclEntry acl = new SimpleAclEntry(recipient, objectIdentity,
null, 0);
AclObjectIdentity objectIdentity = new NamedEntityObjectIdentity("domain", "12");
SimpleAclEntry acl = new SimpleAclEntry(recipient, objectIdentity, null, 0);
acl.addPermissions(new int[] {SimpleAclEntry.READ, SimpleAclEntry.WRITE, SimpleAclEntry.CREATE});
try {
@@ -177,10 +166,8 @@ public class SimpleAclEntryTests extends TestCase {
public void testToString() {
String recipient = "marissa";
AclObjectIdentity objectIdentity = new NamedEntityObjectIdentity("domain",
"12");
SimpleAclEntry acl = new SimpleAclEntry(recipient, objectIdentity,
null, 0);
AclObjectIdentity objectIdentity = new NamedEntityObjectIdentity("domain", "12");
SimpleAclEntry acl = new SimpleAclEntry(recipient, objectIdentity, null, 0);
acl.addPermissions(new int[] {SimpleAclEntry.READ, SimpleAclEntry.WRITE, SimpleAclEntry.CREATE});
assertTrue(acl.toString().endsWith("marissa=-RWC- ............................111. (14)]"));
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -22,17 +22,17 @@ package org.acegisecurity.acl.basic;
* @version $Id$
*/
public class SomeDomain {
//~ Instance fields ========================================================
//~ Instance fields ================================================================================================
private int id;
//~ Methods ================================================================
public void setId(int id) {
this.id = id;
}
//~ Methods ========================================================================================================
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -28,7 +28,7 @@ import org.acegisecurity.acl.basic.SimpleAclEntry;
* @version $Id$
*/
public class BasicAclEntryHolderTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public BasicAclEntryHolderTests() {
super();
@@ -38,16 +38,16 @@ public class BasicAclEntryHolderTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(BasicAclEntryHolderTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testRejectsNull() throws Exception {
try {
new BasicAclEntryHolder(null);

View File

@@ -36,20 +36,15 @@ import org.springframework.context.ApplicationContext;
* @version $Id$
*/
public class EhCacheBasedAclEntryCacheTests extends TestCase {
//~ Static fields/initializers =============================================
//~ Static fields/initializers =====================================================================================
private static final AclObjectIdentity OBJECT_100 = new NamedEntityObjectIdentity("OBJECT",
"100");
private static final AclObjectIdentity OBJECT_200 = new NamedEntityObjectIdentity("OBJECT",
"200");
private static final BasicAclEntry OBJECT_100_MARISSA = new SimpleAclEntry("marissa",
OBJECT_100, null, 2);
private static final BasicAclEntry OBJECT_100_SCOTT = new SimpleAclEntry("scott",
OBJECT_100, null, 4);
private static final BasicAclEntry OBJECT_200_PETER = new SimpleAclEntry("peter",
OBJECT_200, null, 4);
private static final AclObjectIdentity OBJECT_100 = new NamedEntityObjectIdentity("OBJECT", "100");
private static final AclObjectIdentity OBJECT_200 = new NamedEntityObjectIdentity("OBJECT", "200");
private static final BasicAclEntry OBJECT_100_MARISSA = new SimpleAclEntry("marissa", OBJECT_100, null, 2);
private static final BasicAclEntry OBJECT_100_SCOTT = new SimpleAclEntry("scott", OBJECT_100, null, 4);
private static final BasicAclEntry OBJECT_200_PETER = new SimpleAclEntry("peter", OBJECT_200, null, 4);
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public EhCacheBasedAclEntryCacheTests() {
super();
@@ -59,7 +54,7 @@ public class EhCacheBasedAclEntryCacheTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
private Cache getCache() {
ApplicationContext ctx = MockApplicationContext.getContext();
@@ -84,23 +79,14 @@ public class EhCacheBasedAclEntryCacheTests extends TestCase {
cache.putEntriesInCache(new BasicAclEntry[] {OBJECT_200_PETER});
// Check we can get them from cache again
assertEquals(OBJECT_100_SCOTT,
cache.getEntriesFromCache(
new NamedEntityObjectIdentity("OBJECT", "100"))[0]);
assertEquals(OBJECT_100_MARISSA,
cache.getEntriesFromCache(
new NamedEntityObjectIdentity("OBJECT", "100"))[1]);
assertEquals(OBJECT_200_PETER,
cache.getEntriesFromCache(
new NamedEntityObjectIdentity("OBJECT", "200"))[0]);
assertNull(cache.getEntriesFromCache(
new NamedEntityObjectIdentity("OBJECT", "NOT_IN_CACHE")));
assertEquals(OBJECT_100_SCOTT, cache.getEntriesFromCache(new NamedEntityObjectIdentity("OBJECT", "100"))[0]);
assertEquals(OBJECT_100_MARISSA, cache.getEntriesFromCache(new NamedEntityObjectIdentity("OBJECT", "100"))[1]);
assertEquals(OBJECT_200_PETER, cache.getEntriesFromCache(new NamedEntityObjectIdentity("OBJECT", "200"))[0]);
assertNull(cache.getEntriesFromCache(new NamedEntityObjectIdentity("OBJECT", "NOT_IN_CACHE")));
// Check after eviction we cannot get them from cache
cache.removeEntriesFromCache(new NamedEntityObjectIdentity("OBJECT",
"100"));
assertNull(cache.getEntriesFromCache(
new NamedEntityObjectIdentity("OBJECT", "100")));
cache.removeEntriesFromCache(new NamedEntityObjectIdentity("OBJECT", "100"));
assertNull(cache.getEntriesFromCache(new NamedEntityObjectIdentity("OBJECT", "100")));
}
public void testStartupDetectsMissingCache() throws Exception {

View File

@@ -29,7 +29,7 @@ import org.acegisecurity.acl.basic.SimpleAclEntry;
* @version $Id$
*/
public class NullAclEntryCacheTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public NullAclEntryCacheTests() {
super();
@@ -39,7 +39,7 @@ public class NullAclEntryCacheTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(NullAclEntryCacheTests.class);
@@ -52,9 +52,7 @@ public class NullAclEntryCacheTests extends TestCase {
public void testCacheOperation() throws Exception {
NullAclEntryCache cache = new NullAclEntryCache();
cache.putEntriesInCache(new BasicAclEntry[] {new SimpleAclEntry()});
cache.getEntriesFromCache(new NamedEntityObjectIdentity("not_used",
"not_used"));
cache.removeEntriesFromCache(new NamedEntityObjectIdentity("not_used",
"not_used"));
cache.getEntriesFromCache(new NamedEntityObjectIdentity("not_used", "not_used"));
cache.removeEntriesFromCache(new NamedEntityObjectIdentity("not_used", "not_used"));
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -18,6 +18,7 @@ package org.acegisecurity.acl.basic.jdbc;
import junit.framework.TestCase;
import org.acegisecurity.PopulatedDatabase;
import org.acegisecurity.acl.basic.AclObjectIdentity;
import org.acegisecurity.acl.basic.BasicAclEntry;
import org.acegisecurity.acl.basic.NamedEntityObjectIdentity;
@@ -35,11 +36,11 @@ import java.sql.SQLException;
* @version $Id$
*/
public class JdbcDaoImplTests extends TestCase {
//~ Static fields/initializers =============================================
//~ Static fields/initializers =====================================================================================
public static final String OBJECT_IDENTITY = "org.acegisecurity.acl.DomainObject";
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public JdbcDaoImplTests() {
super();
@@ -49,21 +50,28 @@ public class JdbcDaoImplTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(JdbcDaoImplTests.class);
}
private JdbcDaoImpl makePopulatedJdbcDao() throws Exception {
JdbcDaoImpl dao = new JdbcDaoImpl();
dao.setDataSource(PopulatedDatabase.getDataSource());
dao.afterPropertiesSet();
return dao;
}
public final void setUp() throws Exception {
super.setUp();
}
public void testExceptionThrownIfBasicAclEntryClassNotFound()
throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"7");
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "7");
try {
dao.getAcls(identity);
@@ -76,8 +84,7 @@ public class JdbcDaoImplTests extends TestCase {
public void testGetsEntriesWhichExistInDatabaseAndHaveAcls()
throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"2");
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "2");
BasicAclEntry[] acls = dao.getAcls(identity);
assertEquals(2, acls.length);
}
@@ -85,18 +92,15 @@ public class JdbcDaoImplTests extends TestCase {
public void testGetsEntriesWhichExistInDatabaseButHaveNoAcls()
throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"5");
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "5");
BasicAclEntry[] acls = dao.getAcls(identity);
assertEquals(1, acls.length);
assertEquals(JdbcDaoImpl.RECIPIENT_USED_FOR_INHERITENCE_MARKER,
acls[0].getRecipient());
assertEquals(JdbcDaoImpl.RECIPIENT_USED_FOR_INHERITENCE_MARKER, acls[0].getRecipient());
}
public void testGetsEntriesWhichHaveNoParent() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"1");
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "1");
BasicAclEntry[] acls = dao.getAcls(identity);
assertEquals(1, acls.length);
assertNull(acls[0].getAclObjectParentIdentity());
@@ -116,8 +120,7 @@ public class JdbcDaoImplTests extends TestCase {
public void testNullReturnedIfEntityNotFound() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"NOT_VALID_ID");
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "NOT_VALID_ID");
BasicAclEntry[] result = dao.getAcls(identity);
assertNull(result);
}
@@ -131,15 +134,7 @@ public class JdbcDaoImplTests extends TestCase {
assertNull(dao.getAcls(identity));
}
private JdbcDaoImpl makePopulatedJdbcDao() throws Exception {
JdbcDaoImpl dao = new JdbcDaoImpl();
dao.setDataSource(PopulatedDatabase.getDataSource());
dao.afterPropertiesSet();
return dao;
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockMappingSqlQuery extends MappingSqlQuery {
protected Object mapRow(ResultSet arg0, int arg1)

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -18,6 +18,7 @@ package org.acegisecurity.acl.basic.jdbc;
import junit.framework.TestCase;
import org.acegisecurity.PopulatedDatabase;
import org.acegisecurity.acl.basic.AclObjectIdentity;
import org.acegisecurity.acl.basic.BasicAclEntry;
import org.acegisecurity.acl.basic.NamedEntityObjectIdentity;
@@ -39,11 +40,11 @@ import java.sql.SQLException;
* @version $Id$
*/
public class JdbcExtendedDaoImplTests extends TestCase {
//~ Static fields/initializers =============================================
//~ Static fields/initializers =====================================================================================
public static final String OBJECT_IDENTITY = "org.acegisecurity.acl.DomainObject";
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public JdbcExtendedDaoImplTests() {
super();
@@ -53,31 +54,36 @@ public class JdbcExtendedDaoImplTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(JdbcExtendedDaoImplTests.class);
}
private JdbcExtendedDaoImpl makePopulatedJdbcDao()
throws Exception {
JdbcExtendedDaoImpl dao = new JdbcExtendedDaoImpl();
dao.setDataSource(PopulatedDatabase.getDataSource());
dao.afterPropertiesSet();
return dao;
}
public final void setUp() throws Exception {
super.setUp();
}
public void testChangeMask() throws Exception {
JdbcExtendedDaoImpl dao = makePopulatedJdbcDao();
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"204");
AclObjectIdentity parentIdentity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"1");
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "204");
AclObjectIdentity parentIdentity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "1");
// Create a BasicAclEntry for this AclObjectIdentity
SimpleAclEntry simpleAcl1 = new SimpleAclEntry("marissa", identity,
parentIdentity, SimpleAclEntry.CREATE);
SimpleAclEntry simpleAcl1 = new SimpleAclEntry("marissa", identity, parentIdentity, SimpleAclEntry.CREATE);
dao.create(simpleAcl1);
// Create another BasicAclEntry for this AclObjectIdentity
SimpleAclEntry simpleAcl2 = new SimpleAclEntry("scott", identity,
parentIdentity, SimpleAclEntry.READ);
SimpleAclEntry simpleAcl2 = new SimpleAclEntry("scott", identity, parentIdentity, SimpleAclEntry.READ);
dao.create(simpleAcl2);
// Check creation was successful
@@ -87,8 +93,7 @@ public class JdbcExtendedDaoImplTests extends TestCase {
assertEquals(SimpleAclEntry.READ, acls[1].getMask());
// Attempt to change mask
dao.changeMask(identity, "marissa",
new Integer(SimpleAclEntry.ADMINISTRATION));
dao.changeMask(identity, "marissa", new Integer(SimpleAclEntry.ADMINISTRATION));
dao.changeMask(identity, "scott", new Integer(SimpleAclEntry.NOTHING));
acls = dao.getAcls(identity);
assertEquals(2, acls.length);
@@ -101,20 +106,16 @@ public class JdbcExtendedDaoImplTests extends TestCase {
public void testChangeMaskThrowsExceptionWhenExistingRecordNotFound()
throws Exception {
JdbcExtendedDaoImpl dao = makePopulatedJdbcDao();
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"205");
AclObjectIdentity parentIdentity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"1");
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "205");
AclObjectIdentity parentIdentity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "1");
// Create at least one record for this AclObjectIdentity
SimpleAclEntry simpleAcl1 = new SimpleAclEntry("marissa", identity,
parentIdentity, SimpleAclEntry.CREATE);
SimpleAclEntry simpleAcl1 = new SimpleAclEntry("marissa", identity, parentIdentity, SimpleAclEntry.CREATE);
dao.create(simpleAcl1);
// Attempt to change mask, but for a recipient we don't have
try {
dao.changeMask(identity, "scott",
new Integer(SimpleAclEntry.ADMINISTRATION));
dao.changeMask(identity, "scott", new Integer(SimpleAclEntry.ADMINISTRATION));
fail("Should have thrown DataRetrievalFailureException");
} catch (DataRetrievalFailureException expected) {
assertTrue(true);
@@ -137,10 +138,8 @@ public class JdbcExtendedDaoImplTests extends TestCase {
public void testCreationOfIdentityThenAclInSeparateInvocations()
throws Exception {
JdbcExtendedDaoImpl dao = makePopulatedJdbcDao();
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"206");
AclObjectIdentity parentIdentity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"1");
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "206");
AclObjectIdentity parentIdentity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "1");
// Create just the object identity (NB: recipient and mask is null)
SimpleAclEntry simpleAcl1 = new SimpleAclEntry();
@@ -154,17 +153,14 @@ public class JdbcExtendedDaoImplTests extends TestCase {
public void testDeletionOfAllRecipients() throws Exception {
JdbcExtendedDaoImpl dao = makePopulatedJdbcDao();
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"203");
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "203");
// Create a BasicAclEntry for this AclObjectIdentity
SimpleAclEntry simpleAcl1 = new SimpleAclEntry("marissa", identity,
null, SimpleAclEntry.CREATE);
SimpleAclEntry simpleAcl1 = new SimpleAclEntry("marissa", identity, null, SimpleAclEntry.CREATE);
dao.create(simpleAcl1);
// Create another BasicAclEntry for this AclObjectIdentity
SimpleAclEntry simpleAcl2 = new SimpleAclEntry("scott", identity, null,
SimpleAclEntry.READ);
SimpleAclEntry simpleAcl2 = new SimpleAclEntry("scott", identity, null, SimpleAclEntry.READ);
dao.create(simpleAcl2);
// Check creation was successful
@@ -178,19 +174,15 @@ public class JdbcExtendedDaoImplTests extends TestCase {
public void testDeletionOfSpecificRecipient() throws Exception {
JdbcExtendedDaoImpl dao = makePopulatedJdbcDao();
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"202");
AclObjectIdentity parentIdentity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"1");
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "202");
AclObjectIdentity parentIdentity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "1");
// Create a BasicAclEntry for this AclObjectIdentity
SimpleAclEntry simpleAcl1 = new SimpleAclEntry("marissa", identity,
parentIdentity, SimpleAclEntry.CREATE);
SimpleAclEntry simpleAcl1 = new SimpleAclEntry("marissa", identity, parentIdentity, SimpleAclEntry.CREATE);
dao.create(simpleAcl1);
// Create another BasicAclEntry for this AclObjectIdentity
SimpleAclEntry simpleAcl2 = new SimpleAclEntry("scott", identity,
parentIdentity, SimpleAclEntry.READ);
SimpleAclEntry simpleAcl2 = new SimpleAclEntry("scott", identity, parentIdentity, SimpleAclEntry.READ);
dao.create(simpleAcl2);
// Check creation was successful
@@ -267,19 +259,15 @@ public class JdbcExtendedDaoImplTests extends TestCase {
public void testNormalCreationAndDuplicateDetection()
throws Exception {
JdbcExtendedDaoImpl dao = makePopulatedJdbcDao();
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"200");
AclObjectIdentity parentIdentity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"1");
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "200");
AclObjectIdentity parentIdentity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "1");
// Create a BasicAclEntry for this AclObjectIdentity
SimpleAclEntry simpleAcl1 = new SimpleAclEntry("marissa", identity,
parentIdentity, SimpleAclEntry.CREATE);
SimpleAclEntry simpleAcl1 = new SimpleAclEntry("marissa", identity, parentIdentity, SimpleAclEntry.CREATE);
dao.create(simpleAcl1);
// Create another BasicAclEntry for this AclObjectIdentity
SimpleAclEntry simpleAcl2 = new SimpleAclEntry("scott", identity,
parentIdentity, SimpleAclEntry.READ);
SimpleAclEntry simpleAcl2 = new SimpleAclEntry("scott", identity, parentIdentity, SimpleAclEntry.READ);
dao.create(simpleAcl2);
// Check creation was successful
@@ -301,12 +289,9 @@ public class JdbcExtendedDaoImplTests extends TestCase {
public void testRejectsInvalidParent() throws Exception {
JdbcExtendedDaoImpl dao = makePopulatedJdbcDao();
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"201");
AclObjectIdentity parentIdentity = new NamedEntityObjectIdentity(OBJECT_IDENTITY,
"987987987987986");
SimpleAclEntry simpleAcl = new SimpleAclEntry("marissa", identity,
parentIdentity, SimpleAclEntry.CREATE);
AclObjectIdentity identity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "201");
AclObjectIdentity parentIdentity = new NamedEntityObjectIdentity(OBJECT_IDENTITY, "987987987987986");
SimpleAclEntry simpleAcl = new SimpleAclEntry("marissa", identity, parentIdentity, SimpleAclEntry.CREATE);
try {
dao.create(simpleAcl);
@@ -316,16 +301,7 @@ public class JdbcExtendedDaoImplTests extends TestCase {
}
}
private JdbcExtendedDaoImpl makePopulatedJdbcDao()
throws Exception {
JdbcExtendedDaoImpl dao = new JdbcExtendedDaoImpl();
dao.setDataSource(PopulatedDatabase.getDataSource());
dao.afterPropertiesSet();
return dao;
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockMappingSqlQuery extends MappingSqlQuery {
protected Object mapRow(ResultSet arg0, int arg1)

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -28,7 +28,7 @@ import org.acegisecurity.GrantedAuthorityImpl;
* @version $Id$
*/
public class AbstractAdapterAuthenticationTokenTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AbstractAdapterAuthenticationTokenTests() {
super();
@@ -38,31 +38,27 @@ public class AbstractAdapterAuthenticationTokenTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AbstractAdapterAuthenticationTokenTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testGetters() throws Exception {
MockDecisionManagerImpl token = new MockDecisionManagerImpl("my_password",
"Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
MockDecisionManagerImpl token = new MockDecisionManagerImpl("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());
}
public void testIsUserInRole() throws Exception {
MockDecisionManagerImpl token = new MockDecisionManagerImpl("my_password",
"Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
MockDecisionManagerImpl token = new MockDecisionManagerImpl("my_password", "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertTrue(token.isUserInRole("ROLE_ONE"));
assertTrue(token.isUserInRole("ROLE_TWO"));
assertTrue(!token.isUserInRole(""));
@@ -72,42 +68,31 @@ public class AbstractAdapterAuthenticationTokenTests extends TestCase {
}
public void testObjectsEquals() throws Exception {
MockDecisionManagerImpl token1 = new MockDecisionManagerImpl("my_password",
"Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
MockDecisionManagerImpl token2 = new MockDecisionManagerImpl("my_password",
"Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
MockDecisionManagerImpl token1 = new MockDecisionManagerImpl("my_password", "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
MockDecisionManagerImpl token2 = new MockDecisionManagerImpl("my_password", "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertEquals(token1, token2);
MockDecisionManagerImpl token3 = new MockDecisionManagerImpl("my_password",
"Test", "Password_Changed",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
MockDecisionManagerImpl token3 = new MockDecisionManagerImpl("my_password", "Test", "Password_Changed",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertTrue(!token1.equals(token3));
MockDecisionManagerImpl token4 = new MockDecisionManagerImpl("my_password",
"Test_Changed", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
MockDecisionManagerImpl token4 = new MockDecisionManagerImpl("my_password", "Test_Changed", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertTrue(!token1.equals(token4));
MockDecisionManagerImpl token5 = new MockDecisionManagerImpl("password_changed",
"Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
MockDecisionManagerImpl token5 = new MockDecisionManagerImpl("password_changed", "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertTrue(!token1.equals(token5));
MockDecisionManagerImpl token6 = new MockDecisionManagerImpl("my_password",
"Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO_CHANGED")});
MockDecisionManagerImpl token6 = new MockDecisionManagerImpl("my_password", "Test", "Password",
new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO_CHANGED")
});
assertTrue(!token1.equals(token6));
MockDecisionManagerImpl token7 = new MockDecisionManagerImpl("my_password",
"Test", "Password",
MockDecisionManagerImpl token7 = new MockDecisionManagerImpl("my_password", "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE")});
assertTrue(!token1.equals(token7));
@@ -116,24 +101,20 @@ public class AbstractAdapterAuthenticationTokenTests extends TestCase {
public void testSetAuthenticatedAlwaysReturnsTrue()
throws Exception {
MockDecisionManagerImpl token = new MockDecisionManagerImpl("my_password",
"Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
MockDecisionManagerImpl token = new MockDecisionManagerImpl("my_password", "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertTrue(token.isAuthenticated());
token.setAuthenticated(false);
assertTrue(token.isAuthenticated());
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockDecisionManagerImpl
extends AbstractAdapterAuthenticationToken {
private class MockDecisionManagerImpl extends AbstractAdapterAuthenticationToken {
private String password;
private String username;
public MockDecisionManagerImpl(String key, String username,
String password, GrantedAuthority[] authorities) {
public MockDecisionManagerImpl(String key, String username, String password, GrantedAuthority[] authorities) {
super(key, authorities);
this.username = username;
this.password = password;

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -26,6 +26,7 @@ import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import java.util.Arrays;
/**
* Tests {@link AuthByAdapterProvider}
*
@@ -33,7 +34,7 @@ import java.util.Arrays;
* @version $Id$
*/
public class AuthByAdapterTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AuthByAdapterTests() {
super();
@@ -43,25 +44,24 @@ public class AuthByAdapterTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AuthByAdapterTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAuthByAdapterProviderCorrectAuthenticationOperation()
throws Exception {
AuthByAdapterProvider provider = new AuthByAdapterProvider();
provider.setKey("my_password");
PrincipalAcegiUserToken token = new PrincipalAcegiUserToken("my_password",
"Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")}, null);
PrincipalAcegiUserToken token = new PrincipalAcegiUserToken("my_password", "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
null);
assertTrue(provider.supports(token.getClass()));
Authentication response = provider.authenticate(token);
@@ -103,15 +103,13 @@ public class AuthByAdapterTests extends TestCase {
provider.setKey("my_password");
// Should fail as UsernamePassword is not interface of AuthByAdapter
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password");
assertTrue(!provider.supports(token.getClass()));
try {
provider.authenticate(token);
fail(
"Should have thrown ClassCastException (supports() false response was ignored)");
fail("Should have thrown ClassCastException (supports() false response was ignored)");
} catch (ClassCastException expected) {
assertTrue(true);
}
@@ -123,8 +121,7 @@ public class AuthByAdapterTests extends TestCase {
provider.setKey("my_password");
// Should fail as PrincipalAcegiUserToken has different key
PrincipalAcegiUserToken token = new PrincipalAcegiUserToken("wrong_password",
"Test", "Password", null, null);
PrincipalAcegiUserToken token = new PrincipalAcegiUserToken("wrong_password", "Test", "Password", null, null);
try {
provider.authenticate(token);

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -35,7 +35,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
* @version $Id$
*/
public class HttpRequestIntegrationFilterTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public HttpRequestIntegrationFilterTests() {
super();
@@ -45,18 +45,26 @@ public class HttpRequestIntegrationFilterTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(HttpRequestIntegrationFilterTests.class);
}
protected void setUp() throws Exception {
super.setUp();
SecurityContextHolder.getContext().setAuthentication(null);
}
protected void tearDown() throws Exception {
super.tearDown();
SecurityContextHolder.getContext().setAuthentication(null);
}
public void testCorrectOperation() throws Exception {
HttpRequestIntegrationFilter filter = new HttpRequestIntegrationFilter();
PrincipalAcegiUserToken principal = new PrincipalAcegiUserToken("key",
"someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_ROLE")},
null);
PrincipalAcegiUserToken principal = new PrincipalAcegiUserToken("key", "someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_ROLE")}, null);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setUserPrincipal(principal);
@@ -67,8 +75,7 @@ public class HttpRequestIntegrationFilterTests extends TestCase {
filter.doFilter(request, response, chain);
if (!(SecurityContextHolder.getContext().getAuthentication() instanceof PrincipalAcegiUserToken)) {
System.out.println(SecurityContextHolder.getContext()
.getAuthentication());
System.out.println(SecurityContextHolder.getContext().getAuthentication());
fail("Should have returned PrincipalAcegiUserToken");
}
@@ -99,14 +106,4 @@ public class HttpRequestIntegrationFilterTests extends TestCase {
filter.doFilter(request, response, chain);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
protected void setUp() throws Exception {
super.setUp();
SecurityContextHolder.getContext().setAuthentication(null);
}
protected void tearDown() throws Exception {
super.tearDown();
SecurityContextHolder.getContext().setAuthentication(null);
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -25,7 +25,7 @@ import java.security.Principal;
* @version $Id$
*/
public class MockPrincipal implements Principal {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public String getName() {
return "MockPrincipal";

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -28,7 +28,7 @@ import org.acegisecurity.GrantedAuthorityImpl;
* @version $Id$
*/
public class PrincipalAcegiUserTokenTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public PrincipalAcegiUserTokenTests() {
super();
@@ -38,21 +38,20 @@ public class PrincipalAcegiUserTokenTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(PrincipalAcegiUserTokenTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testGetters() throws Exception {
PrincipalAcegiUserToken token = new PrincipalAcegiUserToken("my_password",
"Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")}, null);
PrincipalAcegiUserToken token = new PrincipalAcegiUserToken("my_password", "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
null);
assertEquals("Test", token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertEquals("my_password".hashCode(), token.getKeyHash());
@@ -63,10 +62,10 @@ public class PrincipalAcegiUserTokenTests extends TestCase {
Class clazz = PrincipalAcegiUserToken.class;
try {
clazz.getDeclaredConstructor((Class[])null);
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
} catch (NoSuchMethodException expected) {
assertTrue(true);
}
}
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -22,7 +22,9 @@ import org.acegisecurity.Authentication;
import org.acegisecurity.ConfigAttribute;
import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.SecurityConfig;
import org.acegisecurity.intercept.web.FilterInvocation;
import org.acegisecurity.util.SimpleMethodInvocation;
import org.aopalliance.intercept.MethodInvocation;
@@ -38,7 +40,7 @@ import java.util.Vector;
* @version $Id$
*/
public class AfterInvocationProviderManagerTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AfterInvocationProviderManagerTests() {
super();
@@ -48,25 +50,22 @@ public class AfterInvocationProviderManagerTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AfterInvocationProviderManagerTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testCorrectOperation() throws Exception {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector();
list.add(new MockAfterInvocationProvider("swap1",
MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1")));
list.add(new MockAfterInvocationProvider("swap2",
MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP2")));
list.add(new MockAfterInvocationProvider("swap3",
MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1")));
list.add(new MockAfterInvocationProvider("swap2", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP2")));
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
manager.setProviders(list);
assertEquals(list, manager.getProviders());
manager.afterPropertiesSet();
@@ -87,25 +86,16 @@ public class AfterInvocationProviderManagerTests extends TestCase {
ConfigAttributeDefinition attr4 = new ConfigAttributeDefinition();
attr4.addConfigAttribute(new SecurityConfig("NEVER_CAUSES_SWAP"));
assertEquals("swap1",
manager.decide(null, new SimpleMethodInvocation(), attr1,
"content-before-swapping"));
assertEquals("swap1", manager.decide(null, new SimpleMethodInvocation(), attr1, "content-before-swapping"));
assertEquals("swap2",
manager.decide(null, new SimpleMethodInvocation(), attr2,
"content-before-swapping"));
assertEquals("swap2", manager.decide(null, new SimpleMethodInvocation(), attr2, "content-before-swapping"));
assertEquals("swap3",
manager.decide(null, new SimpleMethodInvocation(), attr3,
"content-before-swapping"));
assertEquals("swap3", manager.decide(null, new SimpleMethodInvocation(), attr3, "content-before-swapping"));
assertEquals("content-before-swapping",
manager.decide(null, new SimpleMethodInvocation(), attr4,
"content-before-swapping"));
manager.decide(null, new SimpleMethodInvocation(), attr4, "content-before-swapping"));
assertEquals("swap3",
manager.decide(null, new SimpleMethodInvocation(), attr2and3,
"content-before-swapping"));
assertEquals("swap3", manager.decide(null, new SimpleMethodInvocation(), attr2and3, "content-before-swapping"));
}
public void testRejectsEmptyProvidersList() {
@@ -123,11 +113,9 @@ public class AfterInvocationProviderManagerTests extends TestCase {
public void testRejectsNonAfterInvocationProviders() {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector();
list.add(new MockAfterInvocationProvider("swap1",
MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1")));
list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1")));
list.add(new Integer(45));
list.add(new MockAfterInvocationProvider("swap3",
MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
try {
manager.setProviders(list);
@@ -152,12 +140,9 @@ public class AfterInvocationProviderManagerTests extends TestCase {
throws Exception {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector();
list.add(new MockAfterInvocationProvider("swap1",
MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1")));
list.add(new MockAfterInvocationProvider("swap2",
MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP2")));
list.add(new MockAfterInvocationProvider("swap3",
MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1")));
list.add(new MockAfterInvocationProvider("swap2", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP2")));
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
manager.setProviders(list);
manager.afterPropertiesSet();
@@ -168,12 +153,9 @@ public class AfterInvocationProviderManagerTests extends TestCase {
public void testSupportsSecureObjectIteration() throws Exception {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector();
list.add(new MockAfterInvocationProvider("swap1",
MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1")));
list.add(new MockAfterInvocationProvider("swap2",
MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP2")));
list.add(new MockAfterInvocationProvider("swap3",
MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1")));
list.add(new MockAfterInvocationProvider("swap2", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP2")));
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
manager.setProviders(list);
manager.afterPropertiesSet();
@@ -181,20 +163,18 @@ public class AfterInvocationProviderManagerTests extends TestCase {
assertTrue(manager.supports(MethodInvocation.class));
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
/**
* Always returns the constructor-defined <code>forceReturnObject</code>,
* provided the same configuration attribute was provided. Also stores the
* secure object it supports.
* Always returns the constructor-defined <code>forceReturnObject</code>, provided the same configuration
* attribute was provided. Also stores the secure object it supports.
*/
private class MockAfterInvocationProvider implements AfterInvocationProvider {
private Class secureObject;
private ConfigAttribute configAttribute;
private Object forceReturnObject;
public MockAfterInvocationProvider(Object forceReturnObject,
Class secureObject, ConfigAttribute configAttribute) {
public MockAfterInvocationProvider(Object forceReturnObject, Class secureObject, ConfigAttribute configAttribute) {
this.forceReturnObject = forceReturnObject;
this.secureObject = secureObject;
this.configAttribute = configAttribute;
@@ -202,9 +182,8 @@ public class AfterInvocationProviderManagerTests extends TestCase {
private MockAfterInvocationProvider() {}
public Object decide(Authentication authentication, Object object,
ConfigAttributeDefinition config, Object returnedObject)
throws AccessDeniedException {
public Object decide(Authentication authentication, Object object, ConfigAttributeDefinition config,
Object returnedObject) throws AccessDeniedException {
if (config.contains(configAttribute)) {
return forceReturnObject;
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -21,11 +21,14 @@ import org.acegisecurity.AuthorizationServiceException;
import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.MockAclManager;
import org.acegisecurity.SecurityConfig;
import org.acegisecurity.acl.AclEntry;
import org.acegisecurity.acl.AclManager;
import org.acegisecurity.acl.basic.MockAclObjectIdentity;
import org.acegisecurity.acl.basic.SimpleAclEntry;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.util.SimpleMethodInvocation;
import java.util.List;
@@ -38,36 +41,34 @@ import java.util.Vector;
* @author Ben Alex
* @version $Id$
*/
public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
extends TestCase {
//~ Constructors ===========================================================
public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests extends TestCase {
//~ Constructors ===================================================================================================
public BasicAclEntryAfterInvocationCollectionFilteringProviderTests() {
super();
}
public BasicAclEntryAfterInvocationCollectionFilteringProviderTests(
String arg0) {
public BasicAclEntryAfterInvocationCollectionFilteringProviderTests(String arg0) {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(BasicAclEntryAfterInvocationCollectionFilteringProviderTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testCorrectOperationWhenPrincipalHasIncorrectPermissionToDomainObject()
throws Exception {
// Create an AclManager, granting scott only ADMINISTRATION rights
AclManager aclManager = new MockAclManager("belmont", "scott",
new AclEntry[] {new SimpleAclEntry("scott",
new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION)});
new AclEntry[] {
new SimpleAclEntry("scott", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION)
});
BasicAclEntryAfterInvocationCollectionFilteringProvider provider = new BasicAclEntryAfterInvocationCollectionFilteringProvider();
provider.setAclManager(aclManager);
@@ -81,14 +82,12 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
list.add("brisbane");
// Create the Authentication and Config Attribs we'll be presenting
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("scott",
"NOT_USED");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("scott", "NOT_USED");
ConfigAttributeDefinition attr = new ConfigAttributeDefinition();
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_COLLECTION_READ"));
// Filter
List filteredList = (List) provider.decide(auth,
new SimpleMethodInvocation(), attr, list);
List filteredList = (List) provider.decide(auth, new SimpleMethodInvocation(), attr, list);
assertEquals(0, filteredList.size());
}
@@ -97,12 +96,12 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
throws Exception {
// Create an AclManager
AclManager aclManager = new MockAclManager("belmont", "marissa",
new AclEntry[] {new MockAclEntry(), new SimpleAclEntry(
"marissa", new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION), new SimpleAclEntry(
"marissa", new MockAclObjectIdentity(), null,
SimpleAclEntry.READ), new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE)});
new AclEntry[] {
new MockAclEntry(),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.READ),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE)
});
BasicAclEntryAfterInvocationCollectionFilteringProvider provider = new BasicAclEntryAfterInvocationCollectionFilteringProvider();
provider.setAclManager(aclManager);
@@ -117,14 +116,12 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
list.add("brisbane");
// Create the Authentication and Config Attribs we'll be presenting
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("scott",
"NOT_USED");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("scott", "NOT_USED");
ConfigAttributeDefinition attr = new ConfigAttributeDefinition();
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_COLLECTION_READ"));
// Filter
List filteredList = (List) provider.decide(auth,
new SimpleMethodInvocation(), attr, list);
List filteredList = (List) provider.decide(auth, new SimpleMethodInvocation(), attr, list);
assertEquals(0, filteredList.size());
}
@@ -133,12 +130,12 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
throws Exception {
// Create an AclManager
AclManager aclManager = new MockAclManager("belmont", "marissa",
new AclEntry[] {new MockAclEntry(), new SimpleAclEntry(
"marissa", new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION), new SimpleAclEntry(
"marissa", new MockAclObjectIdentity(), null,
SimpleAclEntry.READ), new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE)});
new AclEntry[] {
new MockAclEntry(),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.READ),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE)
});
BasicAclEntryAfterInvocationCollectionFilteringProvider provider = new BasicAclEntryAfterInvocationCollectionFilteringProvider();
provider.setAclManager(aclManager);
@@ -154,14 +151,12 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
list.add("brisbane");
// Create the Authentication and Config Attribs we'll be presenting
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa",
"NOT_USED");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa", "NOT_USED");
ConfigAttributeDefinition attr = new ConfigAttributeDefinition();
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_COLLECTION_READ"));
// Filter
List filteredList = (List) provider.decide(auth,
new SimpleMethodInvocation(), attr, list);
List filteredList = (List) provider.decide(auth, new SimpleMethodInvocation(), attr, list);
assertEquals(1, filteredList.size());
assertEquals("belmont", filteredList.get(0));
@@ -171,12 +166,12 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
throws Exception {
// Create an AclManager
AclManager aclManager = new MockAclManager("belmont", "marissa",
new AclEntry[] {new MockAclEntry(), new SimpleAclEntry(
"marissa", new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION), new SimpleAclEntry(
"marissa", new MockAclObjectIdentity(), null,
SimpleAclEntry.READ), new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE)});
new AclEntry[] {
new MockAclEntry(),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.READ),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE)
});
BasicAclEntryAfterInvocationCollectionFilteringProvider provider = new BasicAclEntryAfterInvocationCollectionFilteringProvider();
provider.setAclManager(aclManager);
@@ -192,14 +187,12 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
list[3] = "brisbane";
// Create the Authentication and Config Attribs we'll be presenting
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa",
"NOT_USED");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa", "NOT_USED");
ConfigAttributeDefinition attr = new ConfigAttributeDefinition();
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_COLLECTION_READ"));
// Filter
String[] filteredList = (String[]) provider.decide(auth,
new SimpleMethodInvocation(), attr, list);
String[] filteredList = (String[]) provider.decide(auth, new SimpleMethodInvocation(), attr, list);
assertEquals(1, filteredList.length);
assertEquals("belmont", filteredList[0]);
@@ -209,27 +202,25 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
throws Exception {
// Create an AclManager
AclManager aclManager = new MockAclManager("belmont", "marissa",
new AclEntry[] {new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION), new SimpleAclEntry(
"marissa", new MockAclObjectIdentity(), null,
SimpleAclEntry.READ), new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE), new MockAclEntry()});
new AclEntry[] {
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.READ),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE),
new MockAclEntry()
});
BasicAclEntryAfterInvocationCollectionFilteringProvider provider = new BasicAclEntryAfterInvocationCollectionFilteringProvider();
provider.setAclManager(aclManager);
provider.afterPropertiesSet();
// Create the Authentication and Config Attribs we'll be presenting
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa",
"NOT_USED");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa", "NOT_USED");
ConfigAttributeDefinition attr = new ConfigAttributeDefinition();
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_COLLECTION_READ"));
// Filter
try {
provider.decide(auth, new SimpleMethodInvocation(), attr,
new String("RETURN_OBJECT_NOT_COLLECTION"));
provider.decide(auth, new SimpleMethodInvocation(), attr, new String("RETURN_OBJECT_NOT_COLLECTION"));
fail("Should have thrown AuthorizationServiceException");
} catch (AuthorizationServiceException expected) {
assertTrue(true);
@@ -240,26 +231,24 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
throws Exception {
// Create an AclManager
AclManager aclManager = new MockAclManager("belmont", "marissa",
new AclEntry[] {new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION), new SimpleAclEntry(
"marissa", new MockAclObjectIdentity(), null,
SimpleAclEntry.READ), new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE), new MockAclEntry()});
new AclEntry[] {
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.READ),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE),
new MockAclEntry()
});
BasicAclEntryAfterInvocationCollectionFilteringProvider provider = new BasicAclEntryAfterInvocationCollectionFilteringProvider();
provider.setAclManager(aclManager);
provider.afterPropertiesSet();
// Create the Authentication and Config Attribs we'll be presenting
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa",
"NOT_USED");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa", "NOT_USED");
ConfigAttributeDefinition attr = new ConfigAttributeDefinition();
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_COLLECTION_READ"));
// Filter
List filteredList = (List) provider.decide(auth,
new SimpleMethodInvocation(), attr, null);
List filteredList = (List) provider.decide(auth, new SimpleMethodInvocation(), attr, null);
assertNull(filteredList);
}
@@ -268,16 +257,16 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
throws Exception {
// Create an AclManager
AclManager aclManager = new MockAclManager("sydney", "marissa",
new AclEntry[] {new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null, SimpleAclEntry.READ), new MockAclEntry()});
new AclEntry[] {
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.READ),
new MockAclEntry()
});
BasicAclEntryAfterInvocationCollectionFilteringProvider provider = new BasicAclEntryAfterInvocationCollectionFilteringProvider();
provider.setAclManager(aclManager);
assertEquals("AFTER_ACL_COLLECTION_READ",
provider.getProcessConfigAttribute());
assertEquals("AFTER_ACL_COLLECTION_READ", provider.getProcessConfigAttribute());
provider.setProcessConfigAttribute("AFTER_ACL_COLLECTION_ADMIN");
assertEquals("AFTER_ACL_COLLECTION_ADMIN",
provider.getProcessConfigAttribute());
assertEquals("AFTER_ACL_COLLECTION_ADMIN", provider.getProcessConfigAttribute());
provider.afterPropertiesSet();
// Create a Collection containing many items, which only "sydney"
@@ -289,21 +278,17 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
list.add("brisbane");
// Create the Authentication and Config Attribs we'll be presenting
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa",
"NOT_USED");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa", "NOT_USED");
ConfigAttributeDefinition attr = new ConfigAttributeDefinition();
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_COLLECTION_READ"));
// As no matching config attrib, ensure provider doesn't change list
assertEquals(4,
((List) provider.decide(auth, new SimpleMethodInvocation(), attr, list))
.size());
assertEquals(4, ((List) provider.decide(auth, new SimpleMethodInvocation(), attr, list)).size());
// Filter, this time with the conf attrib provider setup to answer
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_COLLECTION_ADMIN"));
List filteredList = (List) provider.decide(auth,
new SimpleMethodInvocation(), attr, list);
List filteredList = (List) provider.decide(auth, new SimpleMethodInvocation(), attr, list);
assertEquals(1, filteredList.size());
assertEquals("sydney", filteredList.get(0));
@@ -313,16 +298,16 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
throws Exception {
// Create an AclManager
AclManager aclManager = new MockAclManager("sydney", "marissa",
new AclEntry[] {new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION), new MockAclEntry()});
new AclEntry[] {
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new MockAclEntry()
});
BasicAclEntryAfterInvocationCollectionFilteringProvider provider = new BasicAclEntryAfterInvocationCollectionFilteringProvider();
provider.setAclManager(aclManager);
assertEquals(SimpleAclEntry.READ, provider.getRequirePermission()[0]);
provider.setRequirePermission(new int[] {SimpleAclEntry.ADMINISTRATION});
assertEquals(SimpleAclEntry.ADMINISTRATION,
provider.getRequirePermission()[0]);
assertEquals(SimpleAclEntry.ADMINISTRATION, provider.getRequirePermission()[0]);
provider.afterPropertiesSet();
// Create a Collection containing many items, which only "sydney"
@@ -334,14 +319,12 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
list.add("brisbane");
// Create the Authentication and Config Attribs we'll be presenting
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa",
"NOT_USED");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa", "NOT_USED");
ConfigAttributeDefinition attr = new ConfigAttributeDefinition();
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_COLLECTION_READ"));
// Filter
List filteredList = (List) provider.decide(auth,
new SimpleMethodInvocation(), attr, list);
List filteredList = (List) provider.decide(auth, new SimpleMethodInvocation(), attr, list);
assertEquals(1, filteredList.size());
assertEquals("sydney", filteredList.get(0));
@@ -362,9 +345,10 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
throws Exception {
BasicAclEntryAfterInvocationCollectionFilteringProvider provider = new BasicAclEntryAfterInvocationCollectionFilteringProvider();
AclManager aclManager = new MockAclManager("sydney", "marissa",
new AclEntry[] {new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION), new MockAclEntry()});
new AclEntry[] {
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new MockAclEntry()
});
provider.setAclManager(aclManager);
provider.setProcessConfigAttribute(null);
@@ -373,8 +357,7 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
provider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("A processConfigAttribute is mandatory",
expected.getMessage());
assertEquals("A processConfigAttribute is mandatory", expected.getMessage());
}
}
@@ -382,9 +365,10 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
throws Exception {
BasicAclEntryAfterInvocationCollectionFilteringProvider provider = new BasicAclEntryAfterInvocationCollectionFilteringProvider();
AclManager aclManager = new MockAclManager("sydney", "marissa",
new AclEntry[] {new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION), new MockAclEntry()});
new AclEntry[] {
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new MockAclEntry()
});
provider.setAclManager(aclManager);
provider.setRequirePermission(null);
@@ -393,17 +377,15 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProviderTests
provider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("One or more requirePermission entries is mandatory",
expected.getMessage());
assertEquals("One or more requirePermission entries is mandatory", expected.getMessage());
}
}
public void testSupportsAnything() {
assertTrue(new BasicAclEntryAfterInvocationCollectionFilteringProvider()
.supports(String.class));
assertTrue(new BasicAclEntryAfterInvocationCollectionFilteringProvider().supports(String.class));
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockAclEntry implements AclEntry {
// just so AclTag iterates some different types of AclEntrys

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -21,11 +21,14 @@ import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.MockAclManager;
import org.acegisecurity.SecurityConfig;
import org.acegisecurity.acl.AclEntry;
import org.acegisecurity.acl.AclManager;
import org.acegisecurity.acl.basic.MockAclObjectIdentity;
import org.acegisecurity.acl.basic.SimpleAclEntry;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.util.SimpleMethodInvocation;
@@ -36,7 +39,7 @@ import org.acegisecurity.util.SimpleMethodInvocation;
* @version $Id$
*/
public class BasicAclEntryAfterInvocationProviderTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public BasicAclEntryAfterInvocationProviderTests() {
super();
@@ -46,31 +49,30 @@ public class BasicAclEntryAfterInvocationProviderTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(BasicAclEntryAfterInvocationProviderTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testCorrectOperationWhenPrincipalHasIncorrectPermissionToDomainObject()
throws Exception {
// Create an AclManager, granting scott only ADMINISTRATION rights
AclManager aclManager = new MockAclManager("belmont", "scott",
new AclEntry[] {new SimpleAclEntry("scott",
new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION)});
new AclEntry[] {
new SimpleAclEntry("scott", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION)
});
BasicAclEntryAfterInvocationProvider provider = new BasicAclEntryAfterInvocationProvider();
provider.setAclManager(aclManager);
provider.afterPropertiesSet();
// Create the Authentication and Config Attribs we'll be presenting
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("scott",
"NOT_USED");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("scott", "NOT_USED");
ConfigAttributeDefinition attr = new ConfigAttributeDefinition();
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_READ"));
@@ -86,20 +88,19 @@ public class BasicAclEntryAfterInvocationProviderTests extends TestCase {
throws Exception {
// Create an AclManager
AclManager aclManager = new MockAclManager("belmont", "marissa",
new AclEntry[] {new MockAclEntry(), new SimpleAclEntry(
"marissa", new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION), new SimpleAclEntry(
"marissa", new MockAclObjectIdentity(), null,
SimpleAclEntry.READ), new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE)});
new AclEntry[] {
new MockAclEntry(),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.READ),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE)
});
BasicAclEntryAfterInvocationProvider provider = new BasicAclEntryAfterInvocationProvider();
provider.setAclManager(aclManager);
provider.afterPropertiesSet();
// Create the Authentication and Config Attribs we'll be presenting
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("scott",
"NOT_USED");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("scott", "NOT_USED");
ConfigAttributeDefinition attr = new ConfigAttributeDefinition();
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_READ"));
@@ -115,12 +116,12 @@ public class BasicAclEntryAfterInvocationProviderTests extends TestCase {
throws Exception {
// Create an AclManager
AclManager aclManager = new MockAclManager("belmont", "marissa",
new AclEntry[] {new MockAclEntry(), new SimpleAclEntry(
"marissa", new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION), new SimpleAclEntry(
"marissa", new MockAclObjectIdentity(), null,
SimpleAclEntry.READ), new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE)});
new AclEntry[] {
new MockAclEntry(),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.READ),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE)
});
BasicAclEntryAfterInvocationProvider provider = new BasicAclEntryAfterInvocationProvider();
provider.setAclManager(aclManager);
@@ -128,34 +129,31 @@ public class BasicAclEntryAfterInvocationProviderTests extends TestCase {
provider.afterPropertiesSet();
// Create the Authentication and Config Attribs we'll be presenting
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa",
"NOT_USED");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa", "NOT_USED");
ConfigAttributeDefinition attr = new ConfigAttributeDefinition();
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_READ"));
// Filter
assertEquals("belmont",
provider.decide(auth, new SimpleMethodInvocation(), attr, "belmont"));
assertEquals("belmont", provider.decide(auth, new SimpleMethodInvocation(), attr, "belmont"));
}
public void testGrantsAccessIfReturnedObjectIsNull()
throws Exception {
// Create an AclManager
AclManager aclManager = new MockAclManager("belmont", "marissa",
new AclEntry[] {new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION), new SimpleAclEntry(
"marissa", new MockAclObjectIdentity(), null,
SimpleAclEntry.READ), new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE), new MockAclEntry()});
new AclEntry[] {
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.READ),
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.DELETE),
new MockAclEntry()
});
BasicAclEntryAfterInvocationProvider provider = new BasicAclEntryAfterInvocationProvider();
provider.setAclManager(aclManager);
provider.afterPropertiesSet();
// Create the Authentication and Config Attribs we'll be presenting
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa",
"NOT_USED");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa", "NOT_USED");
ConfigAttributeDefinition attr = new ConfigAttributeDefinition();
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_READ"));
@@ -167,8 +165,10 @@ public class BasicAclEntryAfterInvocationProviderTests extends TestCase {
throws Exception {
// Create an AclManager
AclManager aclManager = new MockAclManager("sydney", "marissa",
new AclEntry[] {new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null, SimpleAclEntry.READ), new MockAclEntry()});
new AclEntry[] {
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.READ),
new MockAclEntry()
});
BasicAclEntryAfterInvocationProvider provider = new BasicAclEntryAfterInvocationProvider();
provider.setAclManager(aclManager);
@@ -178,46 +178,41 @@ public class BasicAclEntryAfterInvocationProviderTests extends TestCase {
provider.afterPropertiesSet();
// Create the Authentication and Config Attribs we'll be presenting
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa",
"NOT_USED");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa", "NOT_USED");
ConfigAttributeDefinition attr = new ConfigAttributeDefinition();
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_READ"));
// As no matching config attrib, ensure provider returns original obj
assertEquals("sydney",
provider.decide(auth, new SimpleMethodInvocation(), attr, "sydney"));
assertEquals("sydney", provider.decide(auth, new SimpleMethodInvocation(), attr, "sydney"));
// Filter, this time with the conf attrib provider setup to answer
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_ADMIN"));
assertEquals("sydney",
provider.decide(auth, new SimpleMethodInvocation(), attr, "sydney"));
assertEquals("sydney", provider.decide(auth, new SimpleMethodInvocation(), attr, "sydney"));
}
public void testRespectsModificationsToRequirePermissions()
throws Exception {
// Create an AclManager
AclManager aclManager = new MockAclManager("sydney", "marissa",
new AclEntry[] {new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION), new MockAclEntry()});
new AclEntry[] {
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new MockAclEntry()
});
BasicAclEntryAfterInvocationProvider provider = new BasicAclEntryAfterInvocationProvider();
provider.setAclManager(aclManager);
assertEquals(SimpleAclEntry.READ, provider.getRequirePermission()[0]);
provider.setRequirePermission(new int[] {SimpleAclEntry.ADMINISTRATION});
assertEquals(SimpleAclEntry.ADMINISTRATION,
provider.getRequirePermission()[0]);
assertEquals(SimpleAclEntry.ADMINISTRATION, provider.getRequirePermission()[0]);
provider.afterPropertiesSet();
// Create the Authentication and Config Attribs we'll be presenting
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa",
"NOT_USED");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("marissa", "NOT_USED");
ConfigAttributeDefinition attr = new ConfigAttributeDefinition();
attr.addConfigAttribute(new SecurityConfig("AFTER_ACL_READ"));
// Filter
assertEquals("sydney",
provider.decide(auth, new SimpleMethodInvocation(), attr, "sydney"));
assertEquals("sydney", provider.decide(auth, new SimpleMethodInvocation(), attr, "sydney"));
}
public void testStartupDetectsMissingAclManager() throws Exception {
@@ -235,9 +230,10 @@ public class BasicAclEntryAfterInvocationProviderTests extends TestCase {
throws Exception {
BasicAclEntryAfterInvocationProvider provider = new BasicAclEntryAfterInvocationProvider();
AclManager aclManager = new MockAclManager("sydney", "marissa",
new AclEntry[] {new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION), new MockAclEntry()});
new AclEntry[] {
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new MockAclEntry()
});
provider.setAclManager(aclManager);
provider.setProcessConfigAttribute(null);
@@ -246,8 +242,7 @@ public class BasicAclEntryAfterInvocationProviderTests extends TestCase {
provider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("A processConfigAttribute is mandatory",
expected.getMessage());
assertEquals("A processConfigAttribute is mandatory", expected.getMessage());
}
}
@@ -255,9 +250,10 @@ public class BasicAclEntryAfterInvocationProviderTests extends TestCase {
throws Exception {
BasicAclEntryAfterInvocationProvider provider = new BasicAclEntryAfterInvocationProvider();
AclManager aclManager = new MockAclManager("sydney", "marissa",
new AclEntry[] {new SimpleAclEntry("marissa",
new MockAclObjectIdentity(), null,
SimpleAclEntry.ADMINISTRATION), new MockAclEntry()});
new AclEntry[] {
new SimpleAclEntry("marissa", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new MockAclEntry()
});
provider.setAclManager(aclManager);
provider.setRequirePermission(null);
@@ -266,17 +262,15 @@ public class BasicAclEntryAfterInvocationProviderTests extends TestCase {
provider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("One or more requirePermission entries is mandatory",
expected.getMessage());
assertEquals("One or more requirePermission entries is mandatory", expected.getMessage());
}
}
public void testSupportsAnything() {
assertTrue(new BasicAclEntryAfterInvocationProvider().supports(
String.class));
assertTrue(new BasicAclEntryAfterInvocationProvider().supports(String.class));
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockAclEntry implements AclEntry {
// just so AclTag iterates some different types of AclEntrys

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -26,51 +26,43 @@ import org.acegisecurity.captcha.AlwaysTestAfterMaxRequestsCaptchaChannelProcess
* @author $author$
* @version $Revision$
*/
public class AlwaysTestAfterMaxRequestsCaptchaChannelProcessorTests
extends TestCase {
//~ Instance fields ========================================================
public class AlwaysTestAfterMaxRequestsCaptchaChannelProcessorTests extends TestCase {
//~ Instance fields ================================================================================================
AlwaysTestAfterMaxRequestsCaptchaChannelProcessor alwaysTestAfterMaxRequestsCaptchaChannelProcessor;
//~ Methods ================================================================
//~ Methods ========================================================================================================
protected void setUp() throws Exception {
super.setUp();
alwaysTestAfterMaxRequestsCaptchaChannelProcessor = new AlwaysTestAfterMaxRequestsCaptchaChannelProcessor();
}
public void testIsContextValidConcerningHumanity()
throws Exception {
alwaysTestAfterMaxRequestsCaptchaChannelProcessor.setThresold(1);
CaptchaSecurityContextImpl context = new CaptchaSecurityContextImpl();
assertTrue(alwaysTestAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertTrue(alwaysTestAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
context.incrementHumanRestrictedRessoucesRequestsCount();
alwaysTestAfterMaxRequestsCaptchaChannelProcessor.setThresold(-1);
assertFalse(alwaysTestAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertFalse(alwaysTestAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
alwaysTestAfterMaxRequestsCaptchaChannelProcessor.setThresold(3);
assertTrue(alwaysTestAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertTrue(alwaysTestAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
context.incrementHumanRestrictedRessoucesRequestsCount();
assertTrue(alwaysTestAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertTrue(alwaysTestAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
context.incrementHumanRestrictedRessoucesRequestsCount();
assertFalse(alwaysTestAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertFalse(alwaysTestAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
}
public void testNewContext() {
CaptchaSecurityContextImpl context = new CaptchaSecurityContextImpl();
assertFalse(alwaysTestAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertFalse(alwaysTestAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
alwaysTestAfterMaxRequestsCaptchaChannelProcessor.setThresold(1);
assertTrue(alwaysTestAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
}
protected void setUp() throws Exception {
super.setUp();
alwaysTestAfterMaxRequestsCaptchaChannelProcessor = new AlwaysTestAfterMaxRequestsCaptchaChannelProcessor();
assertTrue(alwaysTestAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -21,42 +21,35 @@ import org.acegisecurity.captcha.AlwaysTestAfterTimeInMillisCaptchaChannelProces
/**
* WARNING! This test class make some assumptions concerning the compute speed!
* For example the two following instructions should be computed in the same
* millis or the test is not valid.
* <pre><code>
* context.setHuman();
* WARNING! This test class make some assumptions concerning the compute speed! For example the two following
* instructions should be computed in the same millis or the test is not valid.<pre><code>context.setHuman();
* assertFalse(alwaysTestAfterTimeInMillisCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
* </code></pre>
* This should be the case for most environements unless
*
* <ul>
* <li>
* you run it on a good old TRS-80
* </li>
* <li>
* you start M$office during this test ;)
* </li>
* </ul>
* </code></pre>This should be the case for most environements unless
* <ul>
* <li>you run it on a good old TRS-80</li>
* <li>you start M$office during this test ;)</li>
* </ul>
*/
public class AlwaysTestAfterTimeInMillisCaptchaChannelProcessorTests
extends TestCase {
//~ Instance fields ========================================================
public class AlwaysTestAfterTimeInMillisCaptchaChannelProcessorTests extends TestCase {
//~ Instance fields ================================================================================================
AlwaysTestAfterTimeInMillisCaptchaChannelProcessor alwaysTestAfterTimeInMillisCaptchaChannelProcessor;
//~ Methods ================================================================
//~ Methods ========================================================================================================
protected void setUp() throws Exception {
super.setUp();
alwaysTestAfterTimeInMillisCaptchaChannelProcessor = new AlwaysTestAfterTimeInMillisCaptchaChannelProcessor();
}
public void testEqualsThresold() {
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
assertFalse(alwaysTestAfterTimeInMillisCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertFalse(alwaysTestAfterTimeInMillisCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
//the two following instructions should be computed or the test is not valid (never fails). This should be the case
// for most environements unless if you run it on a good old TRS-80 (thanks mom).
context.setHuman();
assertFalse(alwaysTestAfterTimeInMillisCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertFalse(alwaysTestAfterTimeInMillisCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
}
public void testIsContextValidConcerningHumanity()
@@ -65,11 +58,9 @@ public class AlwaysTestAfterTimeInMillisCaptchaChannelProcessorTests
alwaysTestAfterTimeInMillisCaptchaChannelProcessor.setThresold(100);
context.setHuman();
while ((System.currentTimeMillis()
- context.getLastPassedCaptchaDateInMillis()) < alwaysTestAfterTimeInMillisCaptchaChannelProcessor
while ((System.currentTimeMillis() - context.getLastPassedCaptchaDateInMillis()) < alwaysTestAfterTimeInMillisCaptchaChannelProcessor
.getThresold()) {
assertTrue(alwaysTestAfterTimeInMillisCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertTrue(alwaysTestAfterTimeInMillisCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
context.incrementHumanRestrictedRessoucesRequestsCount();
long now = System.currentTimeMillis();
@@ -79,20 +70,13 @@ public class AlwaysTestAfterTimeInMillisCaptchaChannelProcessorTests
;
}
assertFalse(alwaysTestAfterTimeInMillisCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertFalse(alwaysTestAfterTimeInMillisCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
}
public void testNewContext() {
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
//alwaysTestAfterTimeInMillisCaptchaChannelProcessor.setThresold(10);
assertFalse(alwaysTestAfterTimeInMillisCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
}
protected void setUp() throws Exception {
super.setUp();
alwaysTestAfterTimeInMillisCaptchaChannelProcessor = new AlwaysTestAfterTimeInMillisCaptchaChannelProcessor();
assertFalse(alwaysTestAfterTimeInMillisCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -24,18 +24,21 @@ import junit.framework.TestCase;
* @author $author$
* @version $Revision$
*/
public class AlwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessorTests
extends TestCase {
//~ Instance fields ========================================================
public class AlwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessorTests extends TestCase {
//~ Instance fields ================================================================================================
AlwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor;
//~ Methods ================================================================
//~ Methods ========================================================================================================
protected void setUp() throws Exception {
super.setUp();
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor = new AlwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor();
}
public void testEqualsThresold() {
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
.setThresold(100);
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.setThresold(100);
context.setHuman();
@@ -47,33 +50,29 @@ public class AlwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessorTe
}
context.incrementHumanRestrictedRessoucesRequestsCount();
assertTrue(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
.isContextValidConcerningHumanity(context));
assertTrue(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.isContextValidConcerningHumanity(
context));
context.setHuman();
context.incrementHumanRestrictedRessoucesRequestsCount();
assertFalse(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
.isContextValidConcerningHumanity(context));
assertFalse(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.isContextValidConcerningHumanity(
context));
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
.setThresold(0);
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.setThresold(0);
context.setHuman();
context.incrementHumanRestrictedRessoucesRequestsCount();
assertFalse(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
.isContextValidConcerningHumanity(context));
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
.setThresold(0);
assertFalse(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.isContextValidConcerningHumanity(
context));
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.setThresold(0);
}
public void testIsContextValidConcerningHumanity()
throws Exception {
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
.setThresold(10);
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.setThresold(10);
context.setHuman();
while ((System.currentTimeMillis()
- context.getLastPassedCaptchaDateInMillis()) < (10 * alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
while ((System.currentTimeMillis() - context.getLastPassedCaptchaDateInMillis()) < (10 * alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
.getThresold())) {
assertTrue(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
.isContextValidConcerningHumanity(context));
@@ -82,12 +81,12 @@ public class AlwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessorTe
public void testNewContext() {
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
assertFalse(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
.isContextValidConcerningHumanity(context));
assertFalse(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.isContextValidConcerningHumanity(
context));
context.setHuman();
assertTrue(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
.isContextValidConcerningHumanity(context));
assertTrue(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.isContextValidConcerningHumanity(
context));
}
public void testShouldPassAbove() {
@@ -97,29 +96,20 @@ public class AlwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessorTe
int i = 0;
while ((System.currentTimeMillis()
- context.getLastPassedCaptchaDateInMillis()) < (100 * alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
while ((System.currentTimeMillis() - context.getLastPassedCaptchaDateInMillis()) < (100 * alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
.getThresold())) {
System.out.println((System.currentTimeMillis()
- context.getLastPassedCaptchaDateInMillis()));
System.out.println((System.currentTimeMillis() - context.getLastPassedCaptchaDateInMillis()));
context.incrementHumanRestrictedRessoucesRequestsCount();
i++;
while ((System.currentTimeMillis()
- context.getLastPassedCaptchaDateInMillis()) < (alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
while ((System.currentTimeMillis() - context.getLastPassedCaptchaDateInMillis()) < (alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
.getThresold() * i)) {}
System.out.println((System.currentTimeMillis()
- context.getLastPassedCaptchaDateInMillis()));
System.out.println((System.currentTimeMillis() - context.getLastPassedCaptchaDateInMillis()));
assertTrue(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
.isContextValidConcerningHumanity(context));
}
}
protected void setUp() throws Exception {
super.setUp();
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor = new AlwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor();
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -12,6 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.acegisecurity.captcha;
import junit.framework.TestCase;
@@ -19,7 +20,9 @@ import junit.framework.TestCase;
import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.MockFilterChain;
import org.acegisecurity.SecurityConfig;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.intercept.web.FilterInvocation;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -37,7 +40,21 @@ import javax.servlet.ServletException;
* @version $Id$
*/
public class CaptchaChannelProcessorTemplateTests extends TestCase {
//~ Methods ================================================================
//~ Methods ========================================================================================================
private MockHttpServletResponse decideWithNewResponse(ConfigAttributeDefinition cad,
CaptchaChannelProcessorTemplate processor, MockHttpServletRequest request)
throws IOException, ServletException {
MockHttpServletResponse response;
MockFilterChain chain;
FilterInvocation fi;
response = new MockHttpServletResponse();
chain = new MockFilterChain();
fi = new FilterInvocation(request, response, chain);
processor.decide(fi, cad);
return response;
}
public void setUp() {
SecurityContextHolder.clearContext();
@@ -47,7 +64,6 @@ public class CaptchaChannelProcessorTemplateTests extends TestCase {
SecurityContextHolder.clearContext();
}
public void testContextRedirect() throws Exception {
CaptchaChannelProcessorTemplate processor = new TestHumanityCaptchaChannelProcessor();
processor.setKeyword("X");
@@ -80,8 +96,7 @@ public class CaptchaChannelProcessorTemplateTests extends TestCase {
assertEquals(null, response.getRedirectedUrl());
processor.setKeyword("Y");
response = decideWithNewResponse(cad, processor, request);
assertEquals("http://localhost:8000/demo/jcaptcha.do",
response.getRedirectedUrl());
assertEquals("http://localhost:8000/demo/jcaptcha.do", response.getRedirectedUrl());
context.setHuman();
response = decideWithNewResponse(cad, processor, request);
assertEquals(null, response.getRedirectedUrl());
@@ -189,8 +204,7 @@ public class CaptchaChannelProcessorTemplateTests extends TestCase {
public void testSupports() {
CaptchaChannelProcessorTemplate processor = new TestHumanityCaptchaChannelProcessor();
processor.setKeyword("X");
assertTrue(processor.supports(
new SecurityConfig(processor.getKeyword())));
assertTrue(processor.supports(new SecurityConfig(processor.getKeyword())));
assertTrue(processor.supports(new SecurityConfig("X")));
@@ -199,25 +213,9 @@ public class CaptchaChannelProcessorTemplateTests extends TestCase {
assertFalse(processor.supports(new SecurityConfig("NOT_SUPPORTED")));
}
private MockHttpServletResponse decideWithNewResponse(
ConfigAttributeDefinition cad,
CaptchaChannelProcessorTemplate processor,
MockHttpServletRequest request) throws IOException, ServletException {
MockHttpServletResponse response;
MockFilterChain chain;
FilterInvocation fi;
response = new MockHttpServletResponse();
chain = new MockFilterChain();
fi = new FilterInvocation(request, response, chain);
processor.decide(fi, cad);
//~ Inner Classes ==================================================================================================
return response;
}
//~ Inner Classes ==========================================================
private class TestHumanityCaptchaChannelProcessor
extends CaptchaChannelProcessorTemplate {
private class TestHumanityCaptchaChannelProcessor extends CaptchaChannelProcessorTemplate {
boolean isContextValidConcerningHumanity(CaptchaSecurityContext context) {
return context.isHuman();
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -18,6 +18,7 @@ package org.acegisecurity.captcha;
import junit.framework.TestCase;
import org.acegisecurity.MockPortResolver;
import org.acegisecurity.util.PortMapperImpl;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -36,7 +37,11 @@ import java.util.Map;
* @version $Id$
*/
public class CaptchaEntryPointTests extends TestCase {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(CaptchaEntryPointTests.class);
}
// ~ Methods
// ================================================================
@@ -44,10 +49,6 @@ public class CaptchaEntryPointTests extends TestCase {
super.setUp();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(CaptchaEntryPointTests.class);
}
public void testDetectsMissingCaptchaFormUrl() throws Exception {
CaptchaEntryPoint ep = new CaptchaEntryPoint();
ep.setPortMapper(new PortMapperImpl());
@@ -57,8 +58,7 @@ public class CaptchaEntryPointTests extends TestCase {
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("captchaFormUrl must be specified",
expected.getMessage());
assertEquals("captchaFormUrl must be specified", expected.getMessage());
}
}
@@ -97,8 +97,7 @@ public class CaptchaEntryPointTests extends TestCase {
assertTrue(ep.getPortMapper() != null);
assertTrue(ep.getPortResolver() != null);
assertEquals("original_requestUrl",
ep.getOriginalRequestUrlParameterName());
assertEquals("original_requestUrl", ep.getOriginalRequestUrlParameterName());
ep.setOriginalRequestUrlParameterName("Z");
assertEquals("Z", ep.getOriginalRequestUrlParameterName());
@@ -138,22 +137,19 @@ public class CaptchaEntryPointTests extends TestCase {
ep.afterPropertiesSet();
ep.commence(request, response);
assertEquals("https://www.example.com/bigWebApp/hello",
response.getRedirectedUrl());
assertEquals("https://www.example.com/bigWebApp/hello", response.getRedirectedUrl());
request.setServerPort(8080);
response = new MockHttpServletResponse();
ep.setPortResolver(new MockPortResolver(8080, 8443));
ep.commence(request, response);
assertEquals("https://www.example.com:8443/bigWebApp/hello",
response.getRedirectedUrl());
assertEquals("https://www.example.com:8443/bigWebApp/hello", response.getRedirectedUrl());
// Now test an unusual custom HTTP:HTTPS is handled properly
request.setServerPort(8888);
response = new MockHttpServletResponse();
ep.commence(request, response);
assertEquals("https://www.example.com:8443/bigWebApp/hello",
response.getRedirectedUrl());
assertEquals("https://www.example.com:8443/bigWebApp/hello", response.getRedirectedUrl());
PortMapperImpl portMapper = new PortMapperImpl();
Map map = new HashMap();
@@ -172,8 +168,7 @@ public class CaptchaEntryPointTests extends TestCase {
ep.afterPropertiesSet();
ep.commence(request, response);
assertEquals("https://www.example.com:9999/bigWebApp/hello",
response.getRedirectedUrl());
assertEquals("https://www.example.com:9999/bigWebApp/hello", response.getRedirectedUrl());
}
public void testHttpsOperationFromOriginalHttpsUrl()
@@ -198,15 +193,13 @@ public class CaptchaEntryPointTests extends TestCase {
ep.afterPropertiesSet();
ep.commence(request, response);
assertEquals("https://www.example.com/bigWebApp/hello",
response.getRedirectedUrl());
assertEquals("https://www.example.com/bigWebApp/hello", response.getRedirectedUrl());
request.setServerPort(8443);
response = new MockHttpServletResponse();
ep.setPortResolver(new MockPortResolver(8080, 8443));
ep.commence(request, response);
assertEquals("https://www.example.com:8443/bigWebApp/hello",
response.getRedirectedUrl());
assertEquals("https://www.example.com:8443/bigWebApp/hello", response.getRedirectedUrl());
}
public void testNormalOperation() throws Exception {
@@ -229,8 +222,7 @@ public class CaptchaEntryPointTests extends TestCase {
ep.afterPropertiesSet();
ep.commence(request, response);
assertEquals("http://www.example.com/bigWebApp/hello",
response.getRedirectedUrl());
assertEquals("http://www.example.com/bigWebApp/hello", response.getRedirectedUrl());
}
public void testOperationWhenHttpsRequestsButHttpsPortUnknown()
@@ -259,8 +251,7 @@ public class CaptchaEntryPointTests extends TestCase {
// Response doesn't switch to HTTPS, as we didn't know HTTP port 8888 to
// HTTP port mapping
assertEquals("http://www.example.com:8888/bigWebApp/hello",
response.getRedirectedUrl());
assertEquals("http://www.example.com:8888/bigWebApp/hello", response.getRedirectedUrl());
}
public void testOperationWithOriginalRequestIncludes()
@@ -269,8 +260,7 @@ public class CaptchaEntryPointTests extends TestCase {
ep.setCaptchaFormUrl("/hello");
PortMapperImpl mapper = new PortMapperImpl();
mapper.getTranslatedPortMappings().put(new Integer(8888),
new Integer(1234));
mapper.getTranslatedPortMappings().put(new Integer(8888), new Integer(1234));
ep.setPortMapper(mapper);
ep.setPortResolver(new MockPortResolver(8888, 1234));
@@ -292,16 +282,16 @@ public class CaptchaEntryPointTests extends TestCase {
ep.afterPropertiesSet();
ep.commence(request, response);
assertEquals("http://www.example.com:8888/hello?original_requestUrl="
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8")
+ "&original_request_method=post", response.getRedirectedUrl());
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post",
response.getRedirectedUrl());
// test the query params
request.addParameter("name", "value");
response = new MockHttpServletResponse();
ep.commence(request, response);
assertEquals("http://www.example.com:8888/hello?original_requestUrl="
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8")
+ "&original_request_method=post", response.getRedirectedUrl());
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post",
response.getRedirectedUrl());
// test the multiple query params
ep.setIncludeOriginalParameters(true);
@@ -311,31 +301,26 @@ public class CaptchaEntryPointTests extends TestCase {
response = new MockHttpServletResponse();
ep.commence(request, response);
assertEquals("http://www.example.com:8888/hello?original_requestUrl="
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8")
+ "&original_request_method=post" + "&original_request_parameters="
+ URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post"
+ "&original_request_parameters=" + URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
response.getRedirectedUrl());
// test add parameter to captcha form url??
ep.setCaptchaFormUrl("/hello?toto=titi");
response = new MockHttpServletResponse();
ep.commence(request, response);
assertEquals(
"http://www.example.com:8888/hello?toto=titi&original_requestUrl="
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8")
+ "&original_request_method=post" + "&original_request_parameters="
+ URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
assertEquals("http://www.example.com:8888/hello?toto=titi&original_requestUrl="
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post"
+ "&original_request_parameters=" + URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
response.getRedirectedUrl());
// with forcing!!!
ep.setForceHttps(true);
response = new MockHttpServletResponse();
ep.commence(request, response);
assertEquals(
"https://www.example.com:1234/hello?toto=titi&original_requestUrl="
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8")
+ "&original_request_method=post" + "&original_request_parameters="
+ URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
assertEquals("https://www.example.com:1234/hello?toto=titi&original_requestUrl="
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post"
+ "&original_request_parameters=" + URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
response.getRedirectedUrl());
}
@@ -344,8 +329,7 @@ public class CaptchaEntryPointTests extends TestCase {
ep.setCaptchaFormUrl("https://www.jcaptcha.net/dotest/");
PortMapperImpl mapper = new PortMapperImpl();
mapper.getTranslatedPortMappings().put(new Integer(8888),
new Integer(1234));
mapper.getTranslatedPortMappings().put(new Integer(8888), new Integer(1234));
ep.setPortMapper(mapper);
ep.setPortResolver(new MockPortResolver(8888, 1234));
@@ -369,16 +353,16 @@ public class CaptchaEntryPointTests extends TestCase {
ep.afterPropertiesSet();
ep.commence(request, response);
assertEquals("https://www.jcaptcha.net/dotest/?original_requestUrl="
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8")
+ "&original_request_method=post", response.getRedirectedUrl());
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post",
response.getRedirectedUrl());
// test the query params
request.addParameter("name", "value");
response = new MockHttpServletResponse();
ep.commence(request, response);
assertEquals("https://www.jcaptcha.net/dotest/?original_requestUrl="
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8")
+ "&original_request_method=post", response.getRedirectedUrl());
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post",
response.getRedirectedUrl());
// test the multiple query params
ep.setIncludeOriginalParameters(true);
@@ -387,31 +371,26 @@ public class CaptchaEntryPointTests extends TestCase {
response = new MockHttpServletResponse();
ep.commence(request, response);
assertEquals("https://www.jcaptcha.net/dotest/?original_requestUrl="
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8")
+ "&original_request_method=post" + "&original_request_parameters="
+ URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post"
+ "&original_request_parameters=" + URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
response.getRedirectedUrl());
// test add parameter to captcha form url??
ep.setCaptchaFormUrl("https://www.jcaptcha.net/dotest/?toto=titi");
response = new MockHttpServletResponse();
ep.commence(request, response);
assertEquals(
"https://www.jcaptcha.net/dotest/?toto=titi&original_requestUrl="
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8")
+ "&original_request_method=post" + "&original_request_parameters="
+ URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
assertEquals("https://www.jcaptcha.net/dotest/?toto=titi&original_requestUrl="
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post"
+ "&original_request_parameters=" + URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
response.getRedirectedUrl());
// with forcing!!!
ep.setForceHttps(true);
response = new MockHttpServletResponse();
ep.commence(request, response);
assertEquals(
"https://www.jcaptcha.net/dotest/?toto=titi&original_requestUrl="
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8")
+ "&original_request_method=post" + "&original_request_parameters="
+ URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
assertEquals("https://www.jcaptcha.net/dotest/?toto=titi&original_requestUrl="
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post"
+ "&original_request_parameters=" + URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
response.getRedirectedUrl());
}
}

View File

@@ -25,15 +25,13 @@ import org.acegisecurity.context.SecurityContextImplTests;
* @version $Id$
*/
public class CaptchaSecurityContextImplTests extends SecurityContextImplTests {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public void testDefaultValues() {
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
assertEquals("should not be human", false, context.isHuman());
assertEquals("should be 0", 0,
context.getLastPassedCaptchaDateInMillis());
assertEquals("should be 0", 0,
context.getHumanRestrictedResourcesRequestsCount());
assertEquals("should be 0", 0, context.getLastPassedCaptchaDateInMillis());
assertEquals("should be 0", 0, context.getHumanRestrictedResourcesRequestsCount());
}
public void testEquals() {
@@ -76,31 +74,24 @@ public class CaptchaSecurityContextImplTests extends SecurityContextImplTests {
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
context.setHuman();
assertEquals("should be human", true, context.isHuman());
assertEquals("should be 0", 0,
context.getHumanRestrictedResourcesRequestsCount());
assertEquals("should be 0", 0, context.getHumanRestrictedResourcesRequestsCount());
context.incrementHumanRestrictedRessoucesRequestsCount();
assertEquals("should be 1", 1,
context.getHumanRestrictedResourcesRequestsCount());
assertEquals("should be 1", 1, context.getHumanRestrictedResourcesRequestsCount());
}
public void testResetHuman() {
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
context.setHuman();
assertEquals("should be human", true, context.isHuman());
assertEquals("should be 0", 0,
context.getHumanRestrictedResourcesRequestsCount());
assertEquals("should be 0", 0, context.getHumanRestrictedResourcesRequestsCount());
context.incrementHumanRestrictedRessoucesRequestsCount();
assertEquals("should be 1", 1,
context.getHumanRestrictedResourcesRequestsCount());
assertEquals("should be 1", 1, context.getHumanRestrictedResourcesRequestsCount());
long now = System.currentTimeMillis();
context.setHuman();
assertEquals("should be 0", 0,
context.getHumanRestrictedResourcesRequestsCount());
assertTrue("should be more than 0",
(context.getLastPassedCaptchaDateInMillis() - now) >= 0);
assertTrue("should be less than 0,1 seconde",
(context.getLastPassedCaptchaDateInMillis() - now) < 100);
assertEquals("should be 0", 0, context.getHumanRestrictedResourcesRequestsCount());
assertTrue("should be more than 0", (context.getLastPassedCaptchaDateInMillis() - now) >= 0);
assertTrue("should be less than 0,1 seconde", (context.getLastPassedCaptchaDateInMillis() - now) < 100);
}
public void testSetHuman() {
@@ -108,11 +99,8 @@ public class CaptchaSecurityContextImplTests extends SecurityContextImplTests {
long now = System.currentTimeMillis();
context.setHuman();
assertEquals("should be human", true, context.isHuman());
assertTrue("should be more than 0",
(context.getLastPassedCaptchaDateInMillis() - now) >= 0);
assertTrue("should be less than 0,1 seconde",
(context.getLastPassedCaptchaDateInMillis() - now) < 100);
assertEquals("should be 0", 0,
context.getHumanRestrictedResourcesRequestsCount());
assertTrue("should be more than 0", (context.getLastPassedCaptchaDateInMillis() - now) >= 0);
assertTrue("should be less than 0,1 seconde", (context.getLastPassedCaptchaDateInMillis() - now) < 100);
assertEquals("should be 0", 0, context.getHumanRestrictedResourcesRequestsCount());
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -18,6 +18,7 @@ package org.acegisecurity.captcha;
import junit.framework.TestCase;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.util.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -30,7 +31,7 @@ import org.springframework.mock.web.MockHttpServletRequest;
* @version $Id$
*/
public class CaptchaValidationProcessingFilterTests extends TestCase {
//~ Methods ================================================================
//~ Methods ========================================================================================================
/*
*/

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -22,12 +22,12 @@ package org.acegisecurity.captcha;
* @version $Id$
*/
public class MockCaptchaServiceProxy implements CaptchaServiceProxy {
//~ Instance fields ========================================================
//~ Instance fields ================================================================================================
public boolean hasBeenCalled = false;
public boolean valid = false;
//~ Methods ================================================================
//~ Methods ========================================================================================================
public boolean validateReponseForId(String id, Object response) {
hasBeenCalled = true;

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -26,59 +26,48 @@ import org.acegisecurity.captcha.TestOnceAfterMaxRequestsCaptchaChannelProcessor
* @author $author$
* @version $Revision$
*/
public class TestOnceAfterMaxRequestsCaptchaChannelProcessorTests
extends TestCase {
//~ Instance fields ========================================================
public class TestOnceAfterMaxRequestsCaptchaChannelProcessorTests extends TestCase {
//~ Instance fields ================================================================================================
TestOnceAfterMaxRequestsCaptchaChannelProcessor testOnceAfterMaxRequestsCaptchaChannelProcessor;
//~ Methods ================================================================
//~ Methods ========================================================================================================
protected void setUp() throws Exception {
super.setUp();
testOnceAfterMaxRequestsCaptchaChannelProcessor = new TestOnceAfterMaxRequestsCaptchaChannelProcessor();
}
public void testIsContextValidConcerningHumanity()
throws Exception {
testOnceAfterMaxRequestsCaptchaChannelProcessor.setThresold(1);
CaptchaSecurityContextImpl context = new CaptchaSecurityContextImpl();
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
context.incrementHumanRestrictedRessoucesRequestsCount();
testOnceAfterMaxRequestsCaptchaChannelProcessor.setThresold(-1);
assertFalse(testOnceAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertFalse(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
testOnceAfterMaxRequestsCaptchaChannelProcessor.setThresold(3);
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
context.incrementHumanRestrictedRessoucesRequestsCount();
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
context.incrementHumanRestrictedRessoucesRequestsCount();
assertFalse(testOnceAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertFalse(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
context.setHuman();
for (int i = 0;
i < (2 * testOnceAfterMaxRequestsCaptchaChannelProcessor
.getThresold()); i++) {
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
for (int i = 0; i < (2 * testOnceAfterMaxRequestsCaptchaChannelProcessor.getThresold()); i++) {
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
}
}
public void testNewContext() {
CaptchaSecurityContextImpl context = new CaptchaSecurityContextImpl();
assertFalse(testOnceAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
assertFalse(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
testOnceAfterMaxRequestsCaptchaChannelProcessor.setThresold(1);
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor
.isContextValidConcerningHumanity(context));
}
protected void setUp() throws Exception {
super.setUp();
testOnceAfterMaxRequestsCaptchaChannelProcessor = new TestOnceAfterMaxRequestsCaptchaChannelProcessor();
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
}
}

View File

@@ -34,11 +34,10 @@ import org.springframework.mock.web.MockHttpSession;
* @version $Id$
*/
public class ConcurrentSessionControllerImplTests extends TestCase {
//~ Methods ================================================================
//~ Methods ========================================================================================================
private Authentication createAuthentication(String user, String password) {
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user,
password);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, password);
auth.setDetails(createWebDetails(auth));
return auth;
@@ -64,8 +63,7 @@ public class ConcurrentSessionControllerImplTests extends TestCase {
sc.checkAuthenticationAllowed(auth);
sc.registerSuccessfulAuthentication(auth);
String sessionId1 = ((WebAuthenticationDetails) auth.getDetails())
.getSessionId();
String sessionId1 = ((WebAuthenticationDetails) auth.getDetails()).getSessionId();
assertFalse(registry.getSessionInformation(sessionId1).isExpired());
// Attempt to authenticate again - it should still be successful
@@ -92,8 +90,7 @@ public class ConcurrentSessionControllerImplTests extends TestCase {
sc.checkAuthenticationAllowed(auth3);
sc.registerSuccessfulAuthentication(auth3);
String sessionId3 = ((WebAuthenticationDetails) auth3.getDetails())
.getSessionId();
String sessionId3 = ((WebAuthenticationDetails) auth3.getDetails()).getSessionId();
assertTrue(registry.getSessionInformation(sessionId1).isExpired());
assertFalse(registry.getSessionInformation(sessionId3).isExpired());
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -41,7 +41,7 @@ import javax.servlet.ServletResponse;
* @version $Id$
*/
public class ConcurrentSessionFilterTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public ConcurrentSessionFilterTests() {
super();
@@ -51,7 +51,15 @@ public class ConcurrentSessionFilterTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ 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(ConcurrentSessionFilterTests.class);
@@ -78,8 +86,7 @@ public class ConcurrentSessionFilterTests extends TestCase {
filter.setExpiredUrl("/expired.jsp");
// Test
executeFilterInContainerSimulator(config, filter, request, response,
chain);
executeFilterInContainerSimulator(config, filter, request, response, chain);
assertEquals("/expired.jsp", response.getRedirectedUrl());
}
@@ -125,30 +132,19 @@ public class ConcurrentSessionFilterTests extends TestCase {
SessionRegistry registry = new SessionRegistryImpl();
registry.registerNewSession(session.getId(), "principal");
Date lastRequest = registry.getSessionInformation(session.getId())
.getLastRequest();
Date lastRequest = registry.getSessionInformation(session.getId()).getLastRequest();
filter.setSessionRegistry(registry);
filter.setExpiredUrl("/expired.jsp");
Thread.sleep(1000);
// Test
executeFilterInContainerSimulator(config, filter, request, response,
chain);
executeFilterInContainerSimulator(config, filter, request, response, chain);
assertTrue(registry.getSessionInformation(session.getId())
.getLastRequest().after(lastRequest));
assertTrue(registry.getSessionInformation(session.getId()).getLastRequest().after(lastRequest));
}
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();
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockFilterChain implements FilterChain {
private boolean expectToProceed;

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -27,15 +27,14 @@ import java.util.Date;
* @version $Id$
*/
public class SessionInformationTests extends TestCase {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public void testObject() throws Exception {
Object principal = "Some principal object";
String sessionId = "1234567890";
Date currentDate = new Date();
SessionInformation info = new SessionInformation(principal, sessionId,
currentDate);
SessionInformation info = new SessionInformation(principal, sessionId, currentDate);
assertEquals(principal, info.getPrincipal());
assertEquals(sessionId, info.getSessionId());
assertEquals(currentDate, info.getLastRequest());

View File

@@ -31,7 +31,7 @@ import java.util.Date;
* @version $Id$
*/
public class SessionRegistryImplTests extends TestCase {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public void testEventPublishing() {
MockHttpSession httpSession = new MockHttpSession();
@@ -45,8 +45,7 @@ public class SessionRegistryImplTests extends TestCase {
sessionRegistry.registerNewSession(sessionId, principal);
// Deregister session via an ApplicationEvent
sessionRegistry.onApplicationEvent(new HttpSessionDestroyedEvent(
httpSession));
sessionRegistry.onApplicationEvent(new HttpSessionDestroyedEvent(httpSession));
// Check attempts to retrieve cleared session return null
assertNull(sessionRegistry.getSessionInformation(sessionId));
@@ -78,14 +77,10 @@ public class SessionRegistryImplTests extends TestCase {
sessionRegistry.registerNewSession(sessionId, principal);
// Retrieve existing session by session ID
Date currentDateTime = sessionRegistry.getSessionInformation(sessionId)
.getLastRequest();
assertEquals(principal,
sessionRegistry.getSessionInformation(sessionId).getPrincipal());
assertEquals(sessionId,
sessionRegistry.getSessionInformation(sessionId).getSessionId());
assertNotNull(sessionRegistry.getSessionInformation(sessionId)
.getLastRequest());
Date currentDateTime = sessionRegistry.getSessionInformation(sessionId).getLastRequest();
assertEquals(principal, sessionRegistry.getSessionInformation(sessionId).getPrincipal());
assertEquals(sessionId, sessionRegistry.getSessionInformation(sessionId).getSessionId());
assertNotNull(sessionRegistry.getSessionInformation(sessionId).getLastRequest());
// Retrieve existing session by principal
assertEquals(1, sessionRegistry.getAllSessions(principal, false).length);
@@ -96,13 +91,11 @@ public class SessionRegistryImplTests extends TestCase {
// Update request date/time
sessionRegistry.refreshLastRequest(sessionId);
Date retrieved = sessionRegistry.getSessionInformation(sessionId)
.getLastRequest();
Date retrieved = sessionRegistry.getSessionInformation(sessionId).getLastRequest();
assertTrue(retrieved.after(currentDateTime));
// Check it retrieves correctly when looked up via principal
assertEquals(retrieved,
sessionRegistry.getAllSessions(principal, false)[0].getLastRequest());
assertEquals(retrieved, sessionRegistry.getAllSessions(principal, false)[0].getLastRequest());
// Clear session information
sessionRegistry.removeSessionInformation(sessionId);
@@ -121,14 +114,12 @@ public class SessionRegistryImplTests extends TestCase {
// Register new Session
sessionRegistry.registerNewSession(sessionId1, principal);
assertEquals(1, sessionRegistry.getAllSessions(principal, false).length);
assertEquals(sessionId1,
sessionRegistry.getAllSessions(principal, false)[0].getSessionId());
assertEquals(sessionId1, sessionRegistry.getAllSessions(principal, false)[0].getSessionId());
// Register new Session
sessionRegistry.registerNewSession(sessionId2, principal);
assertEquals(2, sessionRegistry.getAllSessions(principal, false).length);
assertEquals(sessionId2,
sessionRegistry.getAllSessions(principal, false)[1].getSessionId());
assertEquals(sessionId2, sessionRegistry.getAllSessions(principal, false)[1].getSessionId());
// Expire one session
SessionInformation session = sessionRegistry.getSessionInformation(sessionId2);
@@ -148,20 +139,17 @@ public class SessionRegistryImplTests extends TestCase {
// Register new Session
sessionRegistry.registerNewSession(sessionId1, principal);
assertEquals(1, sessionRegistry.getAllSessions(principal, false).length);
assertEquals(sessionId1,
sessionRegistry.getAllSessions(principal, false)[0].getSessionId());
assertEquals(sessionId1, sessionRegistry.getAllSessions(principal, false)[0].getSessionId());
// Register new Session
sessionRegistry.registerNewSession(sessionId2, principal);
assertEquals(2, sessionRegistry.getAllSessions(principal, false).length);
assertEquals(sessionId2,
sessionRegistry.getAllSessions(principal, false)[1].getSessionId());
assertEquals(sessionId2, sessionRegistry.getAllSessions(principal, false)[1].getSessionId());
// Clear session information
sessionRegistry.removeSessionInformation(sessionId1);
assertEquals(1, sessionRegistry.getAllSessions(principal, false).length);
assertEquals(sessionId2,
sessionRegistry.getAllSessions(principal, false)[0].getSessionId());
assertEquals(sessionId2, sessionRegistry.getAllSessions(principal, false)[0].getSessionId());
// Clear final session
sessionRegistry.removeSessionInformation(sessionId2);

View File

@@ -44,7 +44,7 @@ import javax.servlet.ServletResponse;
* @version $Id$
*/
public class HttpSessionContextIntegrationFilterTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public HttpSessionContextIntegrationFilterTests() {
super();
@@ -54,11 +54,11 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
private void executeFilterInContainerSimulator(FilterConfig filterConfig,
Filter filter, ServletRequest request, ServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
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();
@@ -110,10 +110,8 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
public void testExceptionWithinFilterChainStillClearsSecurityContextHolder()
throws Exception {
// Build an Authentication object we simulate came from HttpSession
PrincipalAcegiUserToken sessionPrincipal = new PrincipalAcegiUserToken("key",
"someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_ROLE")},
null);
PrincipalAcegiUserToken sessionPrincipal = new PrincipalAcegiUserToken("key", "someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_ROLE")}, null);
// Build a Context to store in HttpSession (simulating prior request)
SecurityContext sc = new SecurityContextImpl();
@@ -121,13 +119,10 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession()
.setAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY,
sc);
request.getSession().setAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY, sc);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(sessionPrincipal, null,
new IOException());
FilterChain chain = new MockFilterChain(sessionPrincipal, null, new IOException());
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
@@ -136,32 +131,25 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
// Execute filter
try {
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
fail(
"We should have received the IOException thrown inside the filter chain here");
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
fail("We should have received the IOException thrown inside the filter chain here");
} catch (IOException ioe) {
assertTrue(true);
}
// Check the SecurityContextHolder is null, even though an exception was thrown during chain
assertEquals(new SecurityContextImpl(),
SecurityContextHolder.getContext());
assertEquals(new SecurityContextImpl(), SecurityContextHolder.getContext());
}
public void testExistingContextContentsCopiedIntoContextHolderFromSessionAndChangesToContextCopiedBackToSession()
throws Exception {
// Build an Authentication object we simulate came from HttpSession
PrincipalAcegiUserToken sessionPrincipal = new PrincipalAcegiUserToken("key",
"someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_ROLE")},
null);
PrincipalAcegiUserToken sessionPrincipal = new PrincipalAcegiUserToken("key", "someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_ROLE")}, null);
// Build an Authentication object we simulate our Authentication changed it to
PrincipalAcegiUserToken updatedPrincipal = new PrincipalAcegiUserToken("key",
"someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_DIFFERENT_ROLE")},
null);
PrincipalAcegiUserToken updatedPrincipal = new PrincipalAcegiUserToken("key", "someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_DIFFERENT_ROLE")}, null);
// Build a Context to store in HttpSession (simulating prior request)
SecurityContext sc = new SecurityContextImpl();
@@ -169,13 +157,10 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession()
.setAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY,
sc);
request.getSession().setAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY, sc);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(sessionPrincipal,
updatedPrincipal, null);
FilterChain chain = new MockFilterChain(sessionPrincipal, updatedPrincipal, null);
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
@@ -183,23 +168,19 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
filter.afterPropertiesSet();
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
// Obtain new/update Authentication from HttpSession
SecurityContext context = (SecurityContext) request.getSession()
.getAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal,
((SecurityContext) context).getAuthentication());
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
}
public void testHttpSessionCreatedWhenContextHolderChanges()
throws Exception {
// Build an Authentication object we simulate our Authentication changed it to
PrincipalAcegiUserToken updatedPrincipal = new PrincipalAcegiUserToken("key",
"someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_DIFFERENT_ROLE")},
null);
PrincipalAcegiUserToken updatedPrincipal = new PrincipalAcegiUserToken("key", "someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_DIFFERENT_ROLE")}, null);
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -212,14 +193,12 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
filter.afterPropertiesSet();
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
// Obtain new/updated Authentication from HttpSession
SecurityContext context = (SecurityContext) request.getSession(false)
.getAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal,
((SecurityContext) context).getAuthentication());
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
}
public void testHttpSessionEagerlyCreatedWhenDirected()
@@ -236,8 +215,7 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
filter.afterPropertiesSet();
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
// Check the session is not null
assertNotNull(request.getSession(false));
@@ -256,8 +234,7 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
filter.afterPropertiesSet();
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
// Check the session is null
assertNull(request.getSession(false));
@@ -266,16 +243,13 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
public void testHttpSessionWithNonContextInWellKnownLocationIsOverwritten()
throws Exception {
// Build an Authentication object we simulate our Authentication changed it to
PrincipalAcegiUserToken updatedPrincipal = new PrincipalAcegiUserToken("key",
"someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_DIFFERENT_ROLE")},
null);
PrincipalAcegiUserToken updatedPrincipal = new PrincipalAcegiUserToken("key", "someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_DIFFERENT_ROLE")}, null);
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession()
.setAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY,
"NOT_A_CONTEXT_OBJECT");
.setAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY, "NOT_A_CONTEXT_OBJECT");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(null, updatedPrincipal, null);
@@ -286,25 +260,23 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
filter.afterPropertiesSet();
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
// Obtain new/update Authentication from HttpSession
SecurityContext context = (SecurityContext) request.getSession()
.getAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal,
((SecurityContext) context).getAuthentication());
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockFilterChain extends TestCase implements FilterChain {
private Authentication changeContextHolder;
private Authentication expectedOnContextHolder;
private IOException toThrowDuringChain;
public MockFilterChain(Authentication expectedOnContextHolder,
Authentication changeContextHolder, IOException toThrowDuringChain) {
public MockFilterChain(Authentication expectedOnContextHolder, Authentication changeContextHolder,
IOException toThrowDuringChain) {
this.expectedOnContextHolder = expectedOnContextHolder;
this.changeContextHolder = changeContextHolder;
this.toThrowDuringChain = toThrowDuringChain;
@@ -315,8 +287,7 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
public void doFilter(ServletRequest arg0, ServletResponse arg1)
throws IOException, ServletException {
if (expectedOnContextHolder != null) {
assertEquals(expectedOnContextHolder,
SecurityContextHolder.getContext().getAuthentication());
assertEquals(expectedOnContextHolder, SecurityContextHolder.getContext().getAuthentication());
}
if (changeContextHolder != null) {

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -15,12 +15,12 @@
package org.acegisecurity.context;
import java.util.Random;
import junit.framework.ComparisonFailure;
import junit.framework.TestCase;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import junit.framework.ComparisonFailure;
import junit.framework.TestCase;
import java.util.Random;
/**
@@ -30,8 +30,11 @@ import junit.framework.TestCase;
* @version $Id$
*/
public class SecurityContextHolderTests extends TestCase {
//~ Constructors ===========================================================
private static int errors = 0;
//~ Static fields/initializers =====================================================================================
private static int errors = 0;
//~ Constructors ===================================================================================================
public SecurityContextHolderTests() {
super();
@@ -41,19 +44,179 @@ public class SecurityContextHolderTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public final void setUp() throws Exception {
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
private void loadStartAndWaitForThreads(boolean topLevelThread, String prefix, int createThreads,
boolean expectAllThreadsToUseIdenticalAuthentication, boolean expectChildrenToShareAuthenticationWithParent) {
Thread[] threads = new Thread[createThreads];
errors = 0;
if (topLevelThread) {
// PARENT (TOP-LEVEL) THREAD CREATION
if (expectChildrenToShareAuthenticationWithParent) {
// An InheritableThreadLocal
for (int i = 0; i < threads.length; i++) {
if ((i % 2) == 0) {
// Don't inject auth into current thread; neither current thread or child will have authentication
threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, false, true, null);
} else {
// Inject auth into current thread, but not child; current thread will have auth, child will also have auth
threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, false, true,
prefix + "Auth_Parent_" + i);
}
}
} else if (expectAllThreadsToUseIdenticalAuthentication) {
// A global
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("GLOBAL_USERNAME",
"pass"));
for (int i = 0; i < threads.length; i++) {
if ((i % 2) == 0) {
// Don't inject auth into current thread;both current thread and child will have same authentication
threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, true, true,
"GLOBAL_USERNAME");
} else {
// Inject auth into current thread; current thread will have auth, child will also have auth
threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, true, true, "GLOBAL_USERNAME");
}
}
} else {
// A standard ThreadLocal
for (int i = 0; i < threads.length; i++) {
if ((i % 2) == 0) {
// Don't inject auth into current thread; neither current thread or child will have authentication
threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, false, false, null);
} else {
// Inject auth into current thread, but not child; current thread will have auth, child will not have auth
threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, false, false,
prefix + "Auth_Parent_" + i);
}
}
}
} else {
// CHILD THREAD CREATION
if (expectChildrenToShareAuthenticationWithParent || expectAllThreadsToUseIdenticalAuthentication) {
// The children being created are all expected to have security (ie an InheritableThreadLocal/global AND auth was injected into parent)
for (int i = 0; i < threads.length; i++) {
String expectedUsername = prefix;
if (expectAllThreadsToUseIdenticalAuthentication) {
expectedUsername = "GLOBAL_USERNAME";
}
// Don't inject auth into current thread; the current thread will obtain auth from its parent
// NB: As topLevelThread = true, no further child threads will be created
threads[i] = makeThread(prefix + "->child->Inherited_Auth_Child_" + i, false, false,
expectAllThreadsToUseIdenticalAuthentication, false, expectedUsername);
}
} else {
// The children being created are NOT expected to have security (ie not an InheritableThreadLocal OR auth was not injected into parent)
for (int i = 0; i < threads.length; i++) {
// Don't inject auth into current thread; neither current thread or child will have authentication
// NB: As topLevelThread = true, no further child threads will be created
threads[i] = makeThread(prefix + "->child->Unauth_Child_" + i, false, false, false, false, null);
}
}
}
// Start and execute the threads
startAndRun(threads);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(SecurityContextHolderTests.class);
}
private Thread makeThread(final String threadIdentifier, final boolean topLevelThread,
final boolean injectAuthIntoCurrentThread, final boolean expectAllThreadsToUseIdenticalAuthentication,
final boolean expectChildrenToShareAuthenticationWithParent, final String expectedUsername) {
final Random rnd = new Random();
Thread t = new Thread(new Runnable() {
public void run() {
if (injectAuthIntoCurrentThread) {
// Set authentication in this thread
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken(
expectedUsername, "pass"));
//System.out.println(threadIdentifier + " - set to " + SecurityContextHolder.getContext().getAuthentication());
} else {
//System.out.println(threadIdentifier + " - not set (currently " + SecurityContextHolder.getContext().getAuthentication() + ")");
}
// Do some operations in current thread, checking authentication is as expected in the current thread (ie another thread doesn't change it)
for (int i = 0; i < 25; i++) {
String currentUsername = (SecurityContextHolder.getContext().getAuthentication() == null)
? null : SecurityContextHolder.getContext().getAuthentication().getName();
if ((i % 7) == 0) {
System.out.println(threadIdentifier + " at " + i + " username " + currentUsername);
}
try {
TestCase.assertEquals("Failed on iteration " + i + "; Authentication was '"
+ currentUsername + "' but principal was expected to contain username '"
+ expectedUsername + "'", expectedUsername, currentUsername);
} catch (ComparisonFailure err) {
errors++;
throw err;
}
try {
Thread.sleep(rnd.nextInt(250));
} catch (InterruptedException ignore) {}
}
// Load some children threads, checking the authentication is as expected in the children (ie another thread doesn't change it)
if (topLevelThread) {
// Make four children, but we don't want the children to have any more children (so anti-nature, huh?)
if (injectAuthIntoCurrentThread && expectChildrenToShareAuthenticationWithParent) {
loadStartAndWaitForThreads(false, threadIdentifier, 4,
expectAllThreadsToUseIdenticalAuthentication, true);
} else {
loadStartAndWaitForThreads(false, threadIdentifier, 4,
expectAllThreadsToUseIdenticalAuthentication, false);
}
}
}
}, threadIdentifier);
return t;
}
public final void setUp() throws Exception {
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
}
private void startAndRun(Thread[] threads) {
// Start them up
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
// Wait for them to finish
while (stillRunning(threads)) {
try {
Thread.sleep(250);
} catch (InterruptedException ignore) {}
}
}
private boolean stillRunning(Thread[] threads) {
for (int i = 0; i < threads.length; i++) {
if (threads[i].isAlive()) {
return true;
}
}
return false;
}
public void testContextHolderGetterSetterClearer() {
SecurityContext sc = new SecurityContextImpl();
sc.setAuthentication(new UsernamePasswordAuthenticationToken("Foobar","pass"));
sc.setAuthentication(new UsernamePasswordAuthenticationToken("Foobar", "pass"));
SecurityContextHolder.setContext(sc);
assertEquals(sc, SecurityContextHolder.getContext());
SecurityContextHolder.clearContext();
@@ -65,7 +228,7 @@ public class SecurityContextHolderTests extends TestCase {
assertNotNull(SecurityContextHolder.getContext());
SecurityContextHolder.clearContext();
}
public void testRejectsNulls() {
try {
SecurityContextHolder.setContext(null);
@@ -74,170 +237,34 @@ public class SecurityContextHolderTests extends TestCase {
assertTrue(true);
}
}
public void testSynchronizationCustomStrategyLoading() {
SecurityContextHolder.setStrategyName(InheritableThreadLocalSecurityContextHolderStrategy.class.getName());
assertEquals("SecurityContextHolder[strategy='org.acegisecurity.context.InheritableThreadLocalSecurityContextHolderStrategy']", new SecurityContextHolder().toString());
loadStartAndWaitForThreads(true, "Main_", 10, false, true);
assertEquals("Thread errors detected; review log output for details", 0, errors);
assertEquals("SecurityContextHolder[strategy='org.acegisecurity.context.InheritableThreadLocalSecurityContextHolderStrategy']",
new SecurityContextHolder().toString());
loadStartAndWaitForThreads(true, "Main_", 10, false, true);
assertEquals("Thread errors detected; review log output for details", 0, errors);
}
public void testSynchronizationInheritableThreadLocal() throws Exception {
SecurityContextHolder.clearContext();
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
loadStartAndWaitForThreads(true, "Main_", 10, false, true);
assertEquals("Thread errors detected; review log output for details", 0, errors);
}
public void testSynchronizationThreadLocal() throws Exception {
SecurityContextHolder.clearContext();
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_THREADLOCAL);
loadStartAndWaitForThreads(true, "Main_", 10, false, false);
assertEquals("Thread errors detected; review log output for details", 0, errors);
}
public void testSynchronizationGlobal() throws Exception {
SecurityContextHolder.clearContext();
SecurityContextHolder.clearContext();
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
loadStartAndWaitForThreads(true, "Main_", 10, true, false);
assertEquals("Thread errors detected; review log output for details", 0, errors);
loadStartAndWaitForThreads(true, "Main_", 10, true, false);
assertEquals("Thread errors detected; review log output for details", 0, errors);
}
private void loadStartAndWaitForThreads(boolean topLevelThread, String prefix, int createThreads, boolean expectAllThreadsToUseIdenticalAuthentication, boolean expectChildrenToShareAuthenticationWithParent) {
Thread[] threads = new Thread[createThreads];
errors = 0;
if (topLevelThread) {
// PARENT (TOP-LEVEL) THREAD CREATION
if (expectChildrenToShareAuthenticationWithParent) {
// An InheritableThreadLocal
for (int i = 0; i < threads.length; i++) {
if (i % 2 == 0) {
// Don't inject auth into current thread; neither current thread or child will have authentication
threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, false, true, null);
} else {
// Inject auth into current thread, but not child; current thread will have auth, child will also have auth
threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, false, true, prefix + "Auth_Parent_" + i);
}
}
} else if (expectAllThreadsToUseIdenticalAuthentication) {
// A global
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("GLOBAL_USERNAME","pass"));
for (int i = 0; i < threads.length; i++) {
if (i % 2 == 0) {
// Don't inject auth into current thread;both current thread and child will have same authentication
threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, true, true, "GLOBAL_USERNAME");
} else {
// Inject auth into current thread; current thread will have auth, child will also have auth
threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, true, true, "GLOBAL_USERNAME");
}
}
} else {
// A standard ThreadLocal
for (int i = 0; i < threads.length; i++) {
if (i % 2 == 0) {
// Don't inject auth into current thread; neither current thread or child will have authentication
threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, false, false, null);
} else {
// Inject auth into current thread, but not child; current thread will have auth, child will not have auth
threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, false, false, prefix + "Auth_Parent_" + i);
}
}
}
} else {
// CHILD THREAD CREATION
if (expectChildrenToShareAuthenticationWithParent || expectAllThreadsToUseIdenticalAuthentication) {
// The children being created are all expected to have security (ie an InheritableThreadLocal/global AND auth was injected into parent)
for (int i = 0; i < threads.length; i++) {
String expectedUsername = prefix;
if (expectAllThreadsToUseIdenticalAuthentication) {
expectedUsername = "GLOBAL_USERNAME";
}
// Don't inject auth into current thread; the current thread will obtain auth from its parent
// NB: As topLevelThread = true, no further child threads will be created
threads[i] = makeThread(prefix + "->child->Inherited_Auth_Child_" + i, false, false, expectAllThreadsToUseIdenticalAuthentication, false, expectedUsername);
}
} else {
// The children being created are NOT expected to have security (ie not an InheritableThreadLocal OR auth was not injected into parent)
for (int i = 0; i < threads.length; i++) {
// Don't inject auth into current thread; neither current thread or child will have authentication
// NB: As topLevelThread = true, no further child threads will be created
threads[i] = makeThread(prefix + "->child->Unauth_Child_" + i, false, false, false, false, null);
}
}
}
// Start and execute the threads
startAndRun(threads);
}
private void startAndRun(Thread[] threads) {
// Start them up
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
// Wait for them to finish
while (stillRunning(threads)) {
try {
Thread.sleep(250);
} catch (InterruptedException ignore) {}
}
}
private boolean stillRunning(Thread[] threads) {
for (int i = 0; i < threads.length; i++) {
if (threads[i].isAlive()) {
return true;
}
}
return false;
}
private Thread makeThread(final String threadIdentifier, final boolean topLevelThread, final boolean injectAuthIntoCurrentThread, final boolean expectAllThreadsToUseIdenticalAuthentication, final boolean expectChildrenToShareAuthenticationWithParent, final String expectedUsername) {
final Random rnd = new Random();
Thread t = new Thread(new Runnable() {
public void run() {
if (injectAuthIntoCurrentThread) {
// Set authentication in this thread
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(expectedUsername,"pass"));
//System.out.println(threadIdentifier + " - set to " + SecurityContextHolder.getContext().getAuthentication());
} else {
//System.out.println(threadIdentifier + " - not set (currently " + SecurityContextHolder.getContext().getAuthentication() + ")");
}
// Do some operations in current thread, checking authentication is as expected in the current thread (ie another thread doesn't change it)
for (int i = 0; i < 25; i++) {
String currentUsername = SecurityContextHolder.getContext().getAuthentication() == null ? null : SecurityContextHolder.getContext().getAuthentication().getName();
if (i % 7 == 0) {
System.out.println(threadIdentifier + " at " + i + " username " + currentUsername);
}
try {
TestCase.assertEquals("Failed on iteration " + i + "; Authentication was '" + currentUsername + "' but principal was expected to contain username '" + expectedUsername + "'", expectedUsername, currentUsername);
} catch (ComparisonFailure err) {
errors++;
throw err;
}
try {
Thread.sleep(rnd.nextInt(250));
} catch (InterruptedException ignore) {}
}
public void testSynchronizationInheritableThreadLocal()
throws Exception {
SecurityContextHolder.clearContext();
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
loadStartAndWaitForThreads(true, "Main_", 10, false, true);
assertEquals("Thread errors detected; review log output for details", 0, errors);
}
// Load some children threads, checking the authentication is as expected in the children (ie another thread doesn't change it)
if (topLevelThread) {
// Make four children, but we don't want the children to have any more children (so anti-nature, huh?)
if (injectAuthIntoCurrentThread && expectChildrenToShareAuthenticationWithParent) {
loadStartAndWaitForThreads(false, threadIdentifier, 4, expectAllThreadsToUseIdenticalAuthentication, true);
} else {
loadStartAndWaitForThreads(false, threadIdentifier, 4, expectAllThreadsToUseIdenticalAuthentication, false);
}
}
}
}, threadIdentifier);
return t;
public void testSynchronizationThreadLocal() throws Exception {
SecurityContextHolder.clearContext();
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_THREADLOCAL);
loadStartAndWaitForThreads(true, "Main_", 10, false, false);
assertEquals("Thread errors detected; review log output for details", 0, errors);
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -18,6 +18,7 @@ package org.acegisecurity.context;
import junit.framework.TestCase;
import org.acegisecurity.Authentication;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
@@ -28,7 +29,7 @@ import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
* @version $Id$
*/
public class SecurityContextImplTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public SecurityContextImplTests() {
super();
@@ -38,16 +39,16 @@ public class SecurityContextImplTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(SecurityContextImplTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testEmptyObjectsAreEquals() {
SecurityContextImpl obj1 = new SecurityContextImpl();
SecurityContextImpl obj2 = new SecurityContextImpl();
@@ -56,8 +57,7 @@ public class SecurityContextImplTests extends TestCase {
public void testSecurityContextCorrectOperation() {
SecurityContext context = new SecurityContextImpl();
Authentication auth = new UsernamePasswordAuthenticationToken("marissa",
"koala");
Authentication auth = new UsernamePasswordAuthenticationToken("marissa", "koala");
context.setAuthentication(auth);
assertEquals(auth, context.getAuthentication());
assertTrue(context.toString().lastIndexOf("marissa") != -1);

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -18,8 +18,10 @@ package org.acegisecurity.context.httpinvoker;
import junit.framework.TestCase;
import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.context.httpinvoker.AuthenticationSimpleHttpInvokerRequestExecutor;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import java.io.IOException;
@@ -37,9 +39,8 @@ import java.util.Map;
* @author Ben Alex
* @version $Id$
*/
public class AuthenticationSimpleHttpInvokerRequestExecutorTests
extends TestCase {
//~ Constructors ===========================================================
public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCase {
//~ Constructors ===================================================================================================
public AuthenticationSimpleHttpInvokerRequestExecutorTests() {
super();
@@ -49,7 +50,7 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AuthenticationSimpleHttpInvokerRequestExecutorTests.class);
@@ -57,22 +58,19 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests
public void testNormalOperation() throws Exception {
// Setup client-side context
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("Aladdin",
"open sesame");
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("Aladdin", "open sesame");
SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication);
// Create a connection and ensure our executor sets its
// properties correctly
AuthenticationSimpleHttpInvokerRequestExecutor executor = new AuthenticationSimpleHttpInvokerRequestExecutor();
HttpURLConnection conn = new MockHttpURLConnection(new URL(
"http://localhost/"));
HttpURLConnection conn = new MockHttpURLConnection(new URL("http://localhost/"));
executor.prepareConnection(conn, 10);
// Check connection properties
// See http://www.faqs.org/rfcs/rfc1945.html section 11.1 for example
// we are comparing against
assertEquals("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
conn.getRequestProperty("Authorization"));
assertEquals("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", conn.getRequestProperty("Authorization"));
SecurityContextHolder.getContext().setAuthentication(null);
}
@@ -83,15 +81,14 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests
// Create a connection and ensure our executor sets its
// properties correctly
AuthenticationSimpleHttpInvokerRequestExecutor executor = new AuthenticationSimpleHttpInvokerRequestExecutor();
HttpURLConnection conn = new MockHttpURLConnection(new URL(
"http://localhost/"));
HttpURLConnection conn = new MockHttpURLConnection(new URL("http://localhost/"));
executor.prepareConnection(conn, 10);
// Check connection properties (shouldn't be an Authorization header)
assertNull(conn.getRequestProperty("Authorization"));
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockHttpURLConnection extends HttpURLConnection {
private Map requestProperties = new HashMap();
@@ -100,14 +97,6 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests
super(u);
}
public void setRequestProperty(String key, String value) {
requestProperties.put(key, value);
}
public String getRequestProperty(String key) {
return (String) requestProperties.get(key);
}
public void connect() throws IOException {
throw new UnsupportedOperationException("mock not implemented");
}
@@ -116,6 +105,14 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests
throw new UnsupportedOperationException("mock not implemented");
}
public String getRequestProperty(String key) {
return (String) requestProperties.get(key);
}
public void setRequestProperty(String key, String value) {
requestProperties.put(key, value);
}
public boolean usingProxy() {
throw new UnsupportedOperationException("mock not implemented");
}

View File

@@ -32,14 +32,13 @@ import java.lang.reflect.Method;
/**
* Tests {@link ContextPropagatingRemoteInvocation} and {@link
* ContextPropagatingRemoteInvocationFactory}.
* Tests {@link ContextPropagatingRemoteInvocation} and {@link ContextPropagatingRemoteInvocationFactory}.
*
* @author Ben Alex
* @version $Id$
*/
public class ContextPropagatingRemoteInvocationTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public ContextPropagatingRemoteInvocationTests() {
super();
@@ -49,20 +48,17 @@ public class ContextPropagatingRemoteInvocationTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
private ContextPropagatingRemoteInvocation getRemoteInvocation()
throws Exception {
Class clazz = TargetObject.class;
Method method = clazz.getMethod("makeLowerCase",
new Class[] {String.class});
MethodInvocation mi = new SimpleMethodInvocation(method,
new Object[] {"SOME_STRING"});
Method method = clazz.getMethod("makeLowerCase", new Class[] {String.class});
MethodInvocation mi = new SimpleMethodInvocation(method, new Object[] {"SOME_STRING"});
ContextPropagatingRemoteInvocationFactory factory = new ContextPropagatingRemoteInvocationFactory();
return (ContextPropagatingRemoteInvocation) factory
.createRemoteInvocation(mi);
return (ContextPropagatingRemoteInvocation) factory.createRemoteInvocation(mi);
}
public static void main(String[] args) {
@@ -72,10 +68,8 @@ public class ContextPropagatingRemoteInvocationTests extends TestCase {
public void testContextIsResetEvenIfExceptionOccurs()
throws Exception {
// Setup client-side context
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("marissa",
"koala");
SecurityContextHolder.getContext()
.setAuthentication(clientSideAuthentication);
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("marissa", "koala");
SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication);
ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation();
@@ -88,16 +82,13 @@ public class ContextPropagatingRemoteInvocationTests extends TestCase {
// expected
}
assertNull("Authentication must be null ",
SecurityContextHolder.getContext().getAuthentication());
assertNull("Authentication must be null ", SecurityContextHolder.getContext().getAuthentication());
}
public void testNormalOperation() throws Exception {
// Setup client-side context
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("marissa",
"koala");
SecurityContextHolder.getContext()
.setAuthentication(clientSideAuthentication);
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("marissa", "koala");
SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication);
ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation();
@@ -119,7 +110,6 @@ public class ContextPropagatingRemoteInvocationTests extends TestCase {
ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation();
SecurityContextHolder.getContext().setAuthentication(null); // unnecessary, but for explicitness
assertEquals("some_string Authentication empty",
remoteInvocation.invoke(new TargetObject()));
assertEquals("some_string Authentication empty", remoteInvocation.invoke(new TargetObject()));
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -20,6 +20,7 @@ import junit.framework.TestCase;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.DisabledException;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
@@ -30,16 +31,24 @@ import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
* @version $Id$
*/
public class AuthenticationEventTests extends TestCase {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public final void setUp() throws Exception {
super.setUp();
private Authentication getAuthentication() {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("Principal",
"Credentials");
authentication.setDetails("127.0.0.1");
return authentication;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(AuthenticationEventTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAbstractAuthenticationEvent() {
Authentication auth = getAuthentication();
AbstractAuthenticationEvent event = new AuthenticationSuccessEvent(auth);
@@ -49,8 +58,7 @@ public class AuthenticationEventTests extends TestCase {
public void testAbstractAuthenticationFailureEvent() {
Authentication auth = getAuthentication();
AuthenticationException exception = new DisabledException("TEST");
AbstractAuthenticationFailureEvent event = new AuthenticationFailureDisabledEvent(auth,
exception);
AbstractAuthenticationFailureEvent event = new AuthenticationFailureDisabledEvent(auth, exception);
assertEquals(auth, event.getAuthentication());
assertEquals(exception, event.getException());
}
@@ -59,8 +67,7 @@ public class AuthenticationEventTests extends TestCase {
AuthenticationException exception = new DisabledException("TEST");
try {
AuthenticationFailureDisabledEvent event = new AuthenticationFailureDisabledEvent(null,
exception);
AuthenticationFailureDisabledEvent event = new AuthenticationFailureDisabledEvent(null, exception);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
@@ -75,12 +82,4 @@ public class AuthenticationEventTests extends TestCase {
assertTrue(true);
}
}
private Authentication getAuthentication() {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("Principal",
"Credentials");
authentication.setDetails("127.0.0.1");
return authentication;
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -19,6 +19,7 @@ import junit.framework.TestCase;
import org.acegisecurity.Authentication;
import org.acegisecurity.LockedException;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
@@ -29,16 +30,24 @@ import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
* @version $Id$
*/
public class LoggerListenerTests extends TestCase {
//~ Methods ================================================================
//~ Methods ========================================================================================================
public final void setUp() throws Exception {
super.setUp();
private Authentication getAuthentication() {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("Principal",
"Credentials");
authentication.setDetails("127.0.0.1");
return authentication;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(LoggerListenerTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testLogsEvents() {
AuthenticationFailureDisabledEvent event = new AuthenticationFailureDisabledEvent(getAuthentication(),
new LockedException("TEST"));
@@ -46,12 +55,4 @@ public class LoggerListenerTests extends TestCase {
listener.onApplicationEvent(event);
assertTrue(true);
}
private Authentication getAuthentication() {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("Principal",
"Credentials");
authentication.setDetails("127.0.0.1");
return authentication;
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -19,6 +19,7 @@ import junit.framework.TestCase;
import org.acegisecurity.AuthenticationCredentialsNotFoundException;
import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.util.SimpleMethodInvocation;
@@ -29,7 +30,7 @@ import org.acegisecurity.util.SimpleMethodInvocation;
* @version $Id$
*/
public class AuthenticationCredentialsNotFoundEventTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AuthenticationCredentialsNotFoundEventTests() {
super();
@@ -39,7 +40,7 @@ public class AuthenticationCredentialsNotFoundEventTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AuthenticationCredentialsNotFoundEventTests.class);
@@ -47,8 +48,7 @@ public class AuthenticationCredentialsNotFoundEventTests extends TestCase {
public void testRejectsNulls() {
try {
new AuthenticationCredentialsNotFoundEvent(null,
new ConfigAttributeDefinition(),
new AuthenticationCredentialsNotFoundEvent(null, new ConfigAttributeDefinition(),
new AuthenticationCredentialsNotFoundException("test"));
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
@@ -56,16 +56,16 @@ public class AuthenticationCredentialsNotFoundEventTests extends TestCase {
}
try {
new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(),
null, new AuthenticationCredentialsNotFoundException("test"));
new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(), null,
new AuthenticationCredentialsNotFoundException("test"));
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(),
new ConfigAttributeDefinition(), null);
new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(), new ConfigAttributeDefinition(),
null);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -19,8 +19,11 @@ import junit.framework.TestCase;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.event.authorization.AuthorizationFailureEvent;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.util.SimpleMethodInvocation;
@@ -31,7 +34,7 @@ import org.acegisecurity.util.SimpleMethodInvocation;
* @version $Id$
*/
public class AuthorizationFailureEventTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AuthorizationFailureEventTests() {
super();
@@ -41,7 +44,7 @@ public class AuthorizationFailureEventTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AuthorizationFailureEventTests.class);
@@ -49,10 +52,8 @@ public class AuthorizationFailureEventTests extends TestCase {
public void testRejectsNulls() {
try {
new AuthorizationFailureEvent(null,
new ConfigAttributeDefinition(),
new UsernamePasswordAuthenticationToken("foo", "bar"),
new AccessDeniedException("error"));
new AuthorizationFailureEvent(null, new ConfigAttributeDefinition(),
new UsernamePasswordAuthenticationToken("foo", "bar"), new AccessDeniedException("error"));
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
@@ -60,7 +61,14 @@ public class AuthorizationFailureEventTests extends TestCase {
try {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), null,
new UsernamePasswordAuthenticationToken("foo", "bar"),
new UsernamePasswordAuthenticationToken("foo", "bar"), new AccessDeniedException("error"));
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), new ConfigAttributeDefinition(), null,
new AccessDeniedException("error"));
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
@@ -68,17 +76,7 @@ public class AuthorizationFailureEventTests extends TestCase {
}
try {
new AuthorizationFailureEvent(new SimpleMethodInvocation(),
new ConfigAttributeDefinition(), null,
new AccessDeniedException("error"));
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new AuthorizationFailureEvent(new SimpleMethodInvocation(),
new ConfigAttributeDefinition(),
new AuthorizationFailureEvent(new SimpleMethodInvocation(), new ConfigAttributeDefinition(),
new UsernamePasswordAuthenticationToken("foo", "bar"), null);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -18,7 +18,9 @@ package org.acegisecurity.event.authorization;
import junit.framework.TestCase;
import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.util.SimpleMethodInvocation;
@@ -29,7 +31,7 @@ import org.acegisecurity.util.SimpleMethodInvocation;
* @version $Id$
*/
public class AuthorizedEventTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AuthorizedEventTests() {
super();
@@ -39,7 +41,7 @@ public class AuthorizedEventTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AuthorizedEventTests.class);
@@ -63,8 +65,7 @@ public class AuthorizedEventTests extends TestCase {
}
try {
new AuthorizedEvent(new SimpleMethodInvocation(),
new ConfigAttributeDefinition(), null);
new AuthorizedEvent(new SimpleMethodInvocation(), new ConfigAttributeDefinition(), null);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -21,20 +21,21 @@ import org.acegisecurity.MockAccessDecisionManager;
import org.acegisecurity.MockAfterInvocationManager;
import org.acegisecurity.MockAuthenticationManager;
import org.acegisecurity.MockRunAsManager;
import org.acegisecurity.intercept.method.MockMethodDefinitionSource;
import org.acegisecurity.util.SimpleMethodInvocation;
/**
* Tests some {@link AbstractSecurityInterceptor} methods. Most of the testing
* for this class is found in the <code>MethodSecurityInterceptorTests</code>
* class.
* Tests some {@link AbstractSecurityInterceptor} methods. Most of the testing for this class is found in the
* <code>MethodSecurityInterceptorTests</code> class.
*
* @author Ben Alex
* @version $Id$
*/
public class AbstractSecurityInterceptorTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AbstractSecurityInterceptorTests() {
super();
@@ -44,7 +45,7 @@ public class AbstractSecurityInterceptorTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AbstractSecurityInterceptorTests.class);
@@ -80,22 +81,15 @@ public class AbstractSecurityInterceptorTests extends TestCase {
si.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("Subclass must provide a non-null response to getSecureObjectClass()",
expected.getMessage());
assertEquals("Subclass must provide a non-null response to getSecureObjectClass()", expected.getMessage());
}
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockSecurityInterceptorReturnsNull
extends AbstractSecurityInterceptor {
private class MockSecurityInterceptorReturnsNull extends AbstractSecurityInterceptor {
private ObjectDefinitionSource objectDefinitionSource;
public void setObjectDefinitionSource(
ObjectDefinitionSource objectDefinitionSource) {
this.objectDefinitionSource = objectDefinitionSource;
}
public Class getSecureObjectClass() {
return null;
}
@@ -103,16 +97,14 @@ public class AbstractSecurityInterceptorTests extends TestCase {
public ObjectDefinitionSource obtainObjectDefinitionSource() {
return objectDefinitionSource;
}
}
private class MockSecurityInterceptorWhichOnlySupportsStrings
extends AbstractSecurityInterceptor {
private ObjectDefinitionSource objectDefinitionSource;
public void setObjectDefinitionSource(
ObjectDefinitionSource objectDefinitionSource) {
public void setObjectDefinitionSource(ObjectDefinitionSource objectDefinitionSource) {
this.objectDefinitionSource = objectDefinitionSource;
}
}
private class MockSecurityInterceptorWhichOnlySupportsStrings extends AbstractSecurityInterceptor {
private ObjectDefinitionSource objectDefinitionSource;
public Class getSecureObjectClass() {
return String.class;
@@ -121,5 +113,9 @@ public class AbstractSecurityInterceptorTests extends TestCase {
public ObjectDefinitionSource obtainObjectDefinitionSource() {
return objectDefinitionSource;
}
public void setObjectDefinitionSource(ObjectDefinitionSource objectDefinitionSource) {
this.objectDefinitionSource = objectDefinitionSource;
}
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -19,7 +19,9 @@ import junit.framework.TestCase;
import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.SecurityConfig;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.util.SimpleMethodInvocation;
import org.aopalliance.intercept.MethodInvocation;
@@ -32,7 +34,7 @@ import org.aopalliance.intercept.MethodInvocation;
* @version $Id$
*/
public class InterceptorStatusTokenTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public InterceptorStatusTokenTests() {
super();
@@ -42,7 +44,7 @@ public class InterceptorStatusTokenTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(InterceptorStatusTokenTests.class);
@@ -52,7 +54,7 @@ public class InterceptorStatusTokenTests extends TestCase {
Class clazz = InterceptorStatusToken.class;
try {
clazz.getDeclaredConstructor((Class[])null);
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
} catch (NoSuchMethodException expected) {
assertTrue(true);
@@ -65,8 +67,8 @@ public class InterceptorStatusTokenTests extends TestCase {
MethodInvocation mi = new SimpleMethodInvocation();
InterceptorStatusToken token = new InterceptorStatusToken(new UsernamePasswordAuthenticationToken(
"marissa", "koala"), true, attr, mi);
InterceptorStatusToken token = new InterceptorStatusToken(new UsernamePasswordAuthenticationToken("marissa",
"koala"), true, attr, mi);
assertTrue(token.isContextHolderRefreshRequired());
assertEquals(attr, token.getAttr());

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -23,14 +23,13 @@ import org.aopalliance.intercept.MethodInvocation;
/**
* Tests {@link AbstractMethodDefinitionSource} and associated {@link
* ConfigAttributeDefinition}.
* Tests {@link AbstractMethodDefinitionSource} and associated {@link ConfigAttributeDefinition}.
*
* @author Ben Alex
* @version $Id$
*/
public class AbstractMethodDefinitionSourceTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AbstractMethodDefinitionSourceTests() {
super();
@@ -40,25 +39,23 @@ public class AbstractMethodDefinitionSourceTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AbstractMethodDefinitionSourceTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testDoesNotSupportAnotherObject() {
MockMethodDefinitionSource mds = new MockMethodDefinitionSource(false,
true);
MockMethodDefinitionSource mds = new MockMethodDefinitionSource(false, true);
assertFalse(mds.supports(String.class));
}
public void testGetAttributesForANonMethodInvocation() {
MockMethodDefinitionSource mds = new MockMethodDefinitionSource(false,
true);
MockMethodDefinitionSource mds = new MockMethodDefinitionSource(false, true);
try {
mds.getAttributes(new String());
@@ -69,8 +66,7 @@ public class AbstractMethodDefinitionSourceTests extends TestCase {
}
public void testGetAttributesForANullObject() {
MockMethodDefinitionSource mds = new MockMethodDefinitionSource(false,
true);
MockMethodDefinitionSource mds = new MockMethodDefinitionSource(false, true);
try {
mds.getAttributes(null);
@@ -81,8 +77,7 @@ public class AbstractMethodDefinitionSourceTests extends TestCase {
}
public void testGetAttributesForMethodInvocation() {
MockMethodDefinitionSource mds = new MockMethodDefinitionSource(false,
true);
MockMethodDefinitionSource mds = new MockMethodDefinitionSource(false, true);
try {
mds.getAttributes(new SimpleMethodInvocation());
@@ -93,8 +88,7 @@ public class AbstractMethodDefinitionSourceTests extends TestCase {
}
public void testSupportsMethodInvocation() {
MockMethodDefinitionSource mds = new MockMethodDefinitionSource(false,
true);
MockMethodDefinitionSource mds = new MockMethodDefinitionSource(false, true);
assertTrue(mds.supports(MethodInvocation.class));
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -25,9 +25,13 @@ import org.acegisecurity.ITargetObject;
import org.acegisecurity.OtherTargetObject;
import org.acegisecurity.SecurityConfig;
import org.acegisecurity.TargetObject;
import org.acegisecurity.acl.basic.SomeDomain;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.util.SimpleMethodInvocation;
import org.springframework.context.ApplicationContext;
@@ -48,163 +52,20 @@ import java.util.Set;
* @version $Id$
*/
public class MethodDefinitionAttributesTests extends TestCase {
//~ Instance fields ========================================================
//~ Instance fields ================================================================================================
ClassPathXmlApplicationContext applicationContext;
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public MethodDefinitionAttributesTests(String a) {
super(a);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public final void setUp() throws Exception {
super.setUp();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(MethodDefinitionAttributesTests.class);
}
public void testAttributesForInterfaceTargetObject()
private ConfigAttributeDefinition getConfigAttributeDefinition(Class clazz, String methodName, Class[] args)
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 {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_INTERFACE_METHOD_MAKE_UPPER_CASE")});
SecurityContextHolder.getContext().setAuthentication(token);
ITargetObject target = makeInterceptedTarget();
String result = target.makeUpperCase("hello");
assertEquals("HELLO org.acegisecurity.MockRunAsAuthenticationToken true",
result);
SecurityContextHolder.getContext().setAuthentication(null);
}
public void testMethodCallWithoutRunAsReplacement()
throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_INTERFACE_METHOD_MAKE_LOWER_CASE")});
SecurityContextHolder.getContext().setAuthentication(token);
ITargetObject target = makeInterceptedTarget();
String result = target.makeLowerCase("HELLO");
assertEquals("hello org.acegisecurity.providers.UsernamePasswordAuthenticationToken true",
result);
SecurityContextHolder.getContext().setAuthentication(null);
}
public void testNullReturnedIfZeroAttributesDefinedForMethodInvocation()
throws Exception {
// SomeDomain is not defined in the MockAttributes()
// (which getConfigAttributeDefinition refers to)
ConfigAttributeDefinition def = getConfigAttributeDefinition(SomeDomain.class,
"getId", null);
assertNull(def);
}
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());
@@ -218,6 +79,10 @@ public class MethodDefinitionAttributesTests extends TestCase {
return config;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(MethodDefinitionAttributesTests.class);
}
private ITargetObject makeInterceptedTarget() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"org/acegisecurity/intercept/method/applicationContext.xml");
@@ -225,9 +90,130 @@ public class MethodDefinitionAttributesTests extends TestCase {
return (ITargetObject) context.getBean("target");
}
public final void setUp() throws Exception {
super.setUp();
}
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 {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_INTERFACE_METHOD_MAKE_UPPER_CASE")});
SecurityContextHolder.getContext().setAuthentication(token);
ITargetObject target = makeInterceptedTarget();
String result = target.makeUpperCase("hello");
assertEquals("HELLO org.acegisecurity.MockRunAsAuthenticationToken true", result);
SecurityContextHolder.getContext().setAuthentication(null);
}
public void testMethodCallWithoutRunAsReplacement()
throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_INTERFACE_METHOD_MAKE_LOWER_CASE")});
SecurityContextHolder.getContext().setAuthentication(token);
ITargetObject target = makeInterceptedTarget();
String result = target.makeLowerCase("HELLO");
assertEquals("hello org.acegisecurity.providers.UsernamePasswordAuthenticationToken true", result);
SecurityContextHolder.getContext().setAuthentication(null);
}
public void testNullReturnedIfZeroAttributesDefinedForMethodInvocation()
throws Exception {
// SomeDomain is not defined in the MockAttributes()
// (which getConfigAttributeDefinition refers to)
ConfigAttributeDefinition def = getConfigAttributeDefinition(SomeDomain.class, "getId", null);
assertNull(def);
}
/**
* convert a <code>ConfigAttributeDefinition</code> into a set of
* <code>ConfigAttribute</code>(s)
* convert a <code>ConfigAttributeDefinition</code> into a set of <code>ConfigAttribute</code>(s)
*
* @param def the <code>ConfigAttributeDefinition</code> to cover
*

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -31,14 +31,13 @@ import java.util.Iterator;
/**
* Tests {@link MethodDefinitionSourceEditor} and its asociated {@link
* MethodDefinitionMap}.
* Tests {@link MethodDefinitionSourceEditor} and its asociated {@link MethodDefinitionMap}.
*
* @author Ben Alex
* @version $Id$
*/
public class MethodDefinitionSourceEditorTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public MethodDefinitionSourceEditorTests() {
super();
@@ -48,26 +47,24 @@ public class MethodDefinitionSourceEditorTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(MethodDefinitionSourceEditorTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAspectJJointPointLookup() throws Exception {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
editor.setAsText(
"org.acegisecurity.TargetObject.countLength=ROLE_ONE,ROLE_TWO,RUN_AS_ENTRY");
editor.setAsText("org.acegisecurity.TargetObject.countLength=ROLE_ONE,ROLE_TWO,RUN_AS_ENTRY");
MethodDefinitionMap map = (MethodDefinitionMap) editor.getValue();
Class clazz = TargetObject.class;
Method method = clazz.getMethod("countLength",
new Class[] {String.class});
Method method = clazz.getMethod("countLength", new Class[] {String.class});
MockJoinPoint joinPoint = new MockJoinPoint(new TargetObject(), method);
ConfigAttributeDefinition returnedCountLength = map.getAttributes(joinPoint);
@@ -75,8 +72,7 @@ public class MethodDefinitionSourceEditorTests extends TestCase {
ConfigAttributeDefinition expectedCountLength = new ConfigAttributeDefinition();
expectedCountLength.addConfigAttribute(new SecurityConfig("ROLE_ONE"));
expectedCountLength.addConfigAttribute(new SecurityConfig("ROLE_TWO"));
expectedCountLength.addConfigAttribute(new SecurityConfig(
"RUN_AS_ENTRY"));
expectedCountLength.addConfigAttribute(new SecurityConfig("RUN_AS_ENTRY"));
assertEquals(expectedCountLength, returnedCountLength);
}
@@ -106,8 +102,7 @@ public class MethodDefinitionSourceEditorTests extends TestCase {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
try {
editor.setAsText(
"org.acegisecurity.TargetObject.INVALID_METHOD=FOO,BAR");
editor.setAsText("org.acegisecurity.TargetObject.INVALID_METHOD=FOO,BAR");
fail("Should have given IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
@@ -123,22 +118,17 @@ public class MethodDefinitionSourceEditorTests extends TestCase {
MethodDefinitionMap map = (MethodDefinitionMap) editor.getValue();
assertEquals(3, map.getMethodMapSize());
ConfigAttributeDefinition returnedMakeLower = map.getAttributes(new MockMethodInvocation(
TargetObject.class, "makeLowerCase",
new Class[] {String.class}));
ConfigAttributeDefinition returnedMakeLower = map.getAttributes(new MockMethodInvocation(TargetObject.class,
"makeLowerCase", new Class[] {String.class}));
ConfigAttributeDefinition expectedMakeLower = new ConfigAttributeDefinition();
expectedMakeLower.addConfigAttribute(new SecurityConfig(
"ROLE_FROM_INTERFACE"));
expectedMakeLower.addConfigAttribute(new SecurityConfig("ROLE_FROM_INTERFACE"));
assertEquals(expectedMakeLower, returnedMakeLower);
ConfigAttributeDefinition returnedMakeUpper = map.getAttributes(new MockMethodInvocation(
TargetObject.class, "makeUpperCase",
new Class[] {String.class}));
ConfigAttributeDefinition returnedMakeUpper = map.getAttributes(new MockMethodInvocation(TargetObject.class,
"makeUpperCase", new Class[] {String.class}));
ConfigAttributeDefinition expectedMakeUpper = new ConfigAttributeDefinition();
expectedMakeUpper.addConfigAttribute(new SecurityConfig(
"ROLE_FROM_IMPLEMENTATION"));
expectedMakeUpper.addConfigAttribute(new SecurityConfig(
"ROLE_FROM_INTERFACE"));
expectedMakeUpper.addConfigAttribute(new SecurityConfig("ROLE_FROM_IMPLEMENTATION"));
expectedMakeUpper.addConfigAttribute(new SecurityConfig("ROLE_FROM_INTERFACE"));
assertEquals(expectedMakeUpper, returnedMakeUpper);
}
@@ -185,40 +175,34 @@ public class MethodDefinitionSourceEditorTests extends TestCase {
MethodDefinitionMap map = (MethodDefinitionMap) editor.getValue();
assertEquals(5, map.getMethodMapSize());
ConfigAttributeDefinition returnedMakeLower = map.getAttributes(new MockMethodInvocation(
TargetObject.class, "makeLowerCase",
new Class[] {String.class}));
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 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 returnedCountLength = map.getAttributes(new MockMethodInvocation(TargetObject.class,
"countLength", new Class[] {String.class}));
ConfigAttributeDefinition expectedCountLength = new ConfigAttributeDefinition();
expectedCountLength.addConfigAttribute(new SecurityConfig(
"ROLE_GENERAL"));
expectedCountLength.addConfigAttribute(new SecurityConfig("ROLE_GENERAL"));
assertEquals(expectedCountLength, returnedCountLength);
}
public void testNullIsReturnedByMethodDefinitionSourceWhenMethodInvocationNotDefined()
throws Exception {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
editor.setAsText(
"org.acegisecurity.TargetObject.countLength=ROLE_ONE,ROLE_TWO,RUN_AS_ENTRY");
editor.setAsText("org.acegisecurity.TargetObject.countLength=ROLE_ONE,ROLE_TWO,RUN_AS_ENTRY");
MethodDefinitionMap map = (MethodDefinitionMap) editor.getValue();
ConfigAttributeDefinition configAttributeDefinition = map.getAttributes(new MockMethodInvocation(
TargetObject.class, "makeLowerCase",
new Class[] {String.class}));
TargetObject.class, "makeLowerCase", new Class[] {String.class}));
assertNull(configAttributeDefinition);
}
@@ -232,36 +216,33 @@ public class MethodDefinitionSourceEditorTests extends TestCase {
public void testSingleMethodParsing() throws Exception {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
editor.setAsText(
"org.acegisecurity.TargetObject.countLength=ROLE_ONE,ROLE_TWO,RUN_AS_ENTRY");
editor.setAsText("org.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 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"));
expectedCountLength.addConfigAttribute(new SecurityConfig("RUN_AS_ENTRY"));
assertEquals(expectedCountLength, returnedCountLength);
}
//~ Inner Classes ==========================================================
//~ 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 MockMethodInvocation(Class clazz, String methodName, Class[] parameterTypes)
throws NoSuchMethodException {
method = clazz.getMethod(methodName, parameterTypes);
}
public Object[] getArguments() {
return null;
}

View File

@@ -34,14 +34,13 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Tests {@link
* org.acegisecurity.intercept.method.MethodInvocationPrivilegeEvaluator}.
* Tests {@link org.acegisecurity.intercept.method.MethodInvocationPrivilegeEvaluator}.
*
* @author Ben Alex
* @version $Id$
*/
public class MethodInvocationPrivilegeEvaluatorTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public MethodInvocationPrivilegeEvaluatorTests() {
super();
@@ -51,7 +50,7 @@ public class MethodInvocationPrivilegeEvaluatorTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
private Object lookupTargetObject() {
ApplicationContext context = new ClassPathXmlApplicationContext(
@@ -68,17 +67,14 @@ public class MethodInvocationPrivilegeEvaluatorTests extends TestCase {
ApplicationContext context = new ClassPathXmlApplicationContext(
"org/acegisecurity/intercept/method/aopalliance/applicationContext.xml");
return (MethodSecurityInterceptor) context.getBean(
"securityInterceptor");
return (MethodSecurityInterceptor) context.getBean("securityInterceptor");
}
public void testAllowsAccessUsingCreate() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_LOWER")});
Object object = lookupTargetObject();
MethodInvocation mi = MethodInvocationUtils.create(object,
"makeLowerCase", new Object[] {"foobar"});
MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", new Object[] {"foobar"});
MethodSecurityInterceptor interceptor = makeSecurityInterceptor();
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
@@ -90,11 +86,10 @@ public class MethodInvocationPrivilegeEvaluatorTests extends TestCase {
public void testAllowsAccessUsingCreateFromClass()
throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_LOWER")});
MethodInvocation mi = MethodInvocationUtils.createFromClass(ITargetObject.class,
"makeLowerCase", new Class[] {String.class});
MethodInvocation mi = MethodInvocationUtils.createFromClass(ITargetObject.class, "makeLowerCase",
new Class[] {String.class});
MethodSecurityInterceptor interceptor = makeSecurityInterceptor();
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
@@ -105,12 +100,10 @@ public class MethodInvocationPrivilegeEvaluatorTests extends TestCase {
}
public void testDeclinesAccessUsingCreate() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_NOT_HELD")});
Object object = lookupTargetObject();
MethodInvocation mi = MethodInvocationUtils.create(object,
"makeLowerCase", new Object[] {"foobar"});
MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", new Object[] {"foobar"});
MethodSecurityInterceptor interceptor = makeSecurityInterceptor();
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
@@ -122,11 +115,10 @@ public class MethodInvocationPrivilegeEvaluatorTests extends TestCase {
public void testDeclinesAccessUsingCreateFromClass()
throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_NOT_HELD")});
MethodInvocation mi = MethodInvocationUtils.createFromClass(ITargetObject.class,
"makeLowerCase", new Class[] {String.class});
MethodInvocation mi = MethodInvocationUtils.createFromClass(ITargetObject.class, "makeLowerCase",
new Class[] {String.class});
MethodSecurityInterceptor interceptor = makeSecurityInterceptor();
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -37,27 +37,28 @@ import java.util.List;
* @author Ben Alex
*/
public class MockAttributes implements Attributes {
//~ Instance fields ========================================================
//~ 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")});
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 ================================================================
//~ Methods ========================================================================================================
public Collection getAttributes(Class clazz) {
// Emphasise we return null for OtherTargetObject
@@ -94,8 +95,7 @@ public class MockAttributes implements Attributes {
}
if (method.getName().equals("publicMakeLowerCase")) {
throw new UnsupportedOperationException(
"mock support not implemented");
throw new UnsupportedOperationException("mock support not implemented");
}
}
@@ -114,8 +114,7 @@ public class MockAttributes implements Attributes {
}
if (method.getName().equals("publicMakeLowerCase")) {
throw new UnsupportedOperationException(
"mock support not implemented");
throw new UnsupportedOperationException("mock support not implemented");
}
}
@@ -134,8 +133,7 @@ public class MockAttributes implements Attributes {
}
if (method.getName().equals("publicMakeLowerCase")) {
throw new UnsupportedOperationException(
"mock support not implemented");
throw new UnsupportedOperationException("mock support not implemented");
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -32,15 +32,14 @@ import java.util.Vector;
* @version $Id$
*/
public class MockMethodDefinitionSource extends AbstractMethodDefinitionSource {
//~ Instance fields ========================================================
//~ Instance fields ================================================================================================
private List list;
private boolean returnAnIterator;
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public MockMethodDefinitionSource(boolean includeInvalidAttributes,
boolean returnAnIteratorWhenRequested) {
public MockMethodDefinitionSource(boolean includeInvalidAttributes, boolean returnAnIteratorWhenRequested) {
returnAnIterator = returnAnIteratorWhenRequested;
list = new Vector();
@@ -72,7 +71,7 @@ public class MockMethodDefinitionSource extends AbstractMethodDefinitionSource {
super();
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public Iterator getConfigAttributeDefinitions() {
if (returnAnIterator) {

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -18,6 +18,7 @@ package org.acegisecurity.intercept.method.aopalliance;
import junit.framework.TestCase;
import org.acegisecurity.TargetObject;
import org.acegisecurity.intercept.method.MethodDefinitionMap;
import org.acegisecurity.intercept.method.MethodDefinitionSourceEditor;
@@ -33,7 +34,7 @@ import java.lang.reflect.Method;
* @version $Id$
*/
public class MethodDefinitionSourceAdvisorTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public MethodDefinitionSourceAdvisorTests() {
super();
@@ -43,21 +44,32 @@ public class MethodDefinitionSourceAdvisorTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public final void setUp() throws Exception {
super.setUp();
private MethodSecurityInterceptor getInterceptor() {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
editor.setAsText("org.acegisecurity.TargetObject.countLength=ROLE_NOT_USED");
MethodDefinitionMap map = (MethodDefinitionMap) editor.getValue();
MethodSecurityInterceptor msi = new MethodSecurityInterceptor();
msi.setObjectDefinitionSource(map);
return msi;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(MethodDefinitionSourceAdvisorTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAdvisorReturnsFalseWhenMethodInvocationNotDefined()
throws Exception {
Class clazz = TargetObject.class;
Method method = clazz.getMethod("makeLowerCase",
new Class[] {String.class});
Method method = clazz.getMethod("makeLowerCase", new Class[] {String.class});
MethodDefinitionSourceAdvisor advisor = new MethodDefinitionSourceAdvisor(getInterceptor());
assertFalse(advisor.matches(method, clazz));
@@ -66,8 +78,7 @@ public class MethodDefinitionSourceAdvisorTests extends TestCase {
public void testAdvisorReturnsTrueWhenMethodInvocationIsDefined()
throws Exception {
Class clazz = TargetObject.class;
Method method = clazz.getMethod("countLength",
new Class[] {String.class});
Method method = clazz.getMethod("countLength", new Class[] {String.class});
MethodDefinitionSourceAdvisor advisor = new MethodDefinitionSourceAdvisor(getInterceptor());
assertTrue(advisor.matches(method, clazz));
@@ -78,8 +89,7 @@ public class MethodDefinitionSourceAdvisorTests extends TestCase {
try {
new MethodDefinitionSourceAdvisor(msi);
fail(
"Should have detected null ObjectDefinitionSource and thrown AopConfigException");
fail("Should have detected null ObjectDefinitionSource and thrown AopConfigException");
} catch (AopConfigException expected) {
assertTrue(true);
}
@@ -87,8 +97,7 @@ public class MethodDefinitionSourceAdvisorTests extends TestCase {
public void testUnsupportedOperations() throws Throwable {
Class clazz = TargetObject.class;
Method method = clazz.getMethod("countLength",
new Class[] {String.class});
Method method = clazz.getMethod("countLength", new Class[] {String.class});
MethodDefinitionSourceAdvisor.InternalMethodInvocation imi = new MethodDefinitionSourceAdvisor(getInterceptor()).new InternalMethodInvocation(method);
@@ -127,17 +136,4 @@ public class MethodDefinitionSourceAdvisorTests extends TestCase {
assertTrue(true);
}
}
private MethodSecurityInterceptor getInterceptor() {
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
editor.setAsText(
"org.acegisecurity.TargetObject.countLength=ROLE_NOT_USED");
MethodDefinitionMap map = (MethodDefinitionMap) editor.getValue();
MethodSecurityInterceptor msi = new MethodSecurityInterceptor();
msi.setObjectDefinitionSource(map);
return msi;
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -15,9 +15,6 @@
package org.acegisecurity.intercept.method.aopalliance;
import java.lang.reflect.Method;
import java.util.Iterator;
import junit.framework.TestCase;
import org.acegisecurity.AccessDecisionManager;
@@ -36,14 +33,23 @@ import org.acegisecurity.MockAfterInvocationManager;
import org.acegisecurity.MockAuthenticationManager;
import org.acegisecurity.MockRunAsManager;
import org.acegisecurity.RunAsManager;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.intercept.method.AbstractMethodDefinitionSource;
import org.acegisecurity.intercept.method.MockMethodDefinitionSource;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.runas.RunAsManagerImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.lang.reflect.Method;
import java.util.Iterator;
/**
* Tests {@link MethodSecurityInterceptor}.
@@ -52,7 +58,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
* @version $Id$
*/
public class MethodSecurityInterceptorTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public MethodSecurityInterceptorTests() {
super();
@@ -62,17 +68,45 @@ public class MethodSecurityInterceptorTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(MethodSecurityInterceptorTests.class);
}
private ITargetObject makeInterceptedTarget() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"org/acegisecurity/intercept/method/aopalliance/applicationContext.xml");
return (ITargetObject) context.getBean("target");
}
private ITargetObject makeInterceptedTargetRejectsAuthentication() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"org/acegisecurity/intercept/method/aopalliance/applicationContext.xml");
MockAuthenticationManager authenticationManager = new MockAuthenticationManager(false);
MethodSecurityInterceptor si = (MethodSecurityInterceptor) context.getBean("securityInterceptor");
si.setAuthenticationManager(authenticationManager);
return (ITargetObject) context.getBean("target");
}
private ITargetObject makeInterceptedTargetWithoutAnAfterInvocationManager() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"org/acegisecurity/intercept/method/aopalliance/applicationContext.xml");
MethodSecurityInterceptor si = (MethodSecurityInterceptor) context.getBean("securityInterceptor");
si.setAfterInvocationManager(null);
return (ITargetObject) context.getBean("target");
}
public final void setUp() throws Exception {
super.setUp();
SecurityContextHolder.getContext().setAuthentication(null);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(MethodSecurityInterceptorTests.class);
}
public void testCallingAPublicMethodFacadeWillNotRepeatSecurityChecksWhenPassedToTheSecuredMethodItFronts()
throws Exception {
ITargetObject target = makeInterceptedTarget();
@@ -82,21 +116,18 @@ public class MethodSecurityInterceptorTests extends TestCase {
public void testCallingAPublicMethodWhenPresentingAnAuthenticationObjectWillNotChangeItsIsAuthenticatedProperty()
throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password");
assertTrue(!token.isAuthenticated());
SecurityContextHolder.getContext().setAuthentication(token);
// The associated MockAuthenticationManager WILL accept the above UsernamePasswordAuthenticationToken
ITargetObject target = makeInterceptedTarget();
String result = target.publicMakeLowerCase("HELLO");
assertEquals("hello org.acegisecurity.providers.UsernamePasswordAuthenticationToken false",
result);
assertEquals("hello org.acegisecurity.providers.UsernamePasswordAuthenticationToken false", result);
}
public void testDeniesWhenAppropriate() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_NO_BENEFIT_TO_THIS_GRANTED_AUTHORITY")});
SecurityContextHolder.getContext().setAuthentication(token);
@@ -114,8 +145,7 @@ public class MethodSecurityInterceptorTests extends TestCase {
MockAccessDecisionManager accessDecision = new MockAccessDecisionManager();
MockRunAsManager runAs = new MockRunAsManager();
MockAuthenticationManager authManager = new MockAuthenticationManager();
MockMethodDefinitionSource methodSource = new MockMethodDefinitionSource(false,
true);
MockMethodDefinitionSource methodSource = new MockMethodDefinitionSource(false, true);
MockAfterInvocationManager afterInvocation = new MockAfterInvocationManager();
MethodSecurityInterceptor si = new MethodSecurityInterceptor();
@@ -133,21 +163,18 @@ public class MethodSecurityInterceptorTests extends TestCase {
}
public void testMethodCallWithRunAsReplacement() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_UPPER")});
SecurityContextHolder.getContext().setAuthentication(token);
ITargetObject target = makeInterceptedTarget();
String result = target.makeUpperCase("hello");
assertEquals("HELLO org.acegisecurity.MockRunAsAuthenticationToken true",
result);
assertEquals("HELLO org.acegisecurity.MockRunAsAuthenticationToken true", result);
}
public void testMethodCallWithoutRunAsReplacement()
throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_LOWER")});
assertTrue(token.isAuthenticated());
SecurityContextHolder.getContext().setAuthentication(token);
@@ -156,8 +183,7 @@ public class MethodSecurityInterceptorTests extends TestCase {
String result = target.makeLowerCase("HELLO");
// Note we check the isAuthenticated remained true in following line
assertEquals("hello org.acegisecurity.providers.UsernamePasswordAuthenticationToken true",
result);
assertEquals("hello org.acegisecurity.providers.UsernamePasswordAuthenticationToken true", result);
}
public void testRejectionOfEmptySecurityContext() throws Exception {
@@ -165,8 +191,7 @@ public class MethodSecurityInterceptorTests extends TestCase {
try {
target.makeUpperCase("hello");
fail(
"Should have thrown AuthenticationCredentialsNotFoundException");
fail("Should have thrown AuthenticationCredentialsNotFoundException");
} catch (AuthenticationCredentialsNotFoundException expected) {
assertTrue(true);
}
@@ -191,8 +216,7 @@ public class MethodSecurityInterceptorTests extends TestCase {
public void testRejectsCallsWhenAuthenticationIsIncorrect()
throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password");
assertTrue(!token.isAuthenticated());
SecurityContextHolder.getContext().setAuthentication(token);
@@ -266,8 +290,7 @@ public class MethodSecurityInterceptorTests extends TestCase {
si.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("An AccessDecisionManager is required",
expected.getMessage());
assertEquals("An AccessDecisionManager is required", expected.getMessage());
}
}
@@ -284,8 +307,7 @@ public class MethodSecurityInterceptorTests extends TestCase {
si.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("An AuthenticationManager is required",
expected.getMessage());
assertEquals("An AuthenticationManager is required", expected.getMessage());
}
}
@@ -299,8 +321,7 @@ public class MethodSecurityInterceptorTests extends TestCase {
si.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("An ObjectDefinitionSource is required",
expected.getMessage());
assertEquals("An ObjectDefinitionSource is required", expected.getMessage());
}
}
@@ -384,66 +405,12 @@ public class MethodSecurityInterceptorTests extends TestCase {
assertTrue(true);
}
private ITargetObject makeInterceptedTarget() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"org/acegisecurity/intercept/method/aopalliance/applicationContext.xml");
//~ Inner Classes ==================================================================================================
return (ITargetObject) context.getBean("target");
}
private ITargetObject makeInterceptedTargetRejectsAuthentication() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"org/acegisecurity/intercept/method/aopalliance/applicationContext.xml");
MockAuthenticationManager authenticationManager = new MockAuthenticationManager(false);
MethodSecurityInterceptor si = (MethodSecurityInterceptor) context
.getBean("securityInterceptor");
si.setAuthenticationManager(authenticationManager);
return (ITargetObject) context.getBean("target");
}
private ITargetObject makeInterceptedTargetWithoutAnAfterInvocationManager() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"org/acegisecurity/intercept/method/aopalliance/applicationContext.xml");
MethodSecurityInterceptor si = (MethodSecurityInterceptor) context
.getBean("securityInterceptor");
si.setAfterInvocationManager(null);
return (ITargetObject) context.getBean("target");
}
//~ Inner Classes ==========================================================
private class MockAccessDecisionManagerWhichOnlySupportsStrings
implements AccessDecisionManager {
public void decide(Authentication authentication, Object object,
ConfigAttributeDefinition config) throws AccessDeniedException {
throw new UnsupportedOperationException(
"mock method not implemented");
}
public boolean supports(Class clazz) {
if (String.class.isAssignableFrom(clazz)) {
return true;
} else {
return false;
}
}
public boolean supports(ConfigAttribute attribute) {
return true;
}
}
private class MockAfterInvocationManagerWhichOnlySupportsStrings
implements AfterInvocationManager {
public Object decide(Authentication authentication, Object object,
ConfigAttributeDefinition config, Object returnedObject)
private class MockAccessDecisionManagerWhichOnlySupportsStrings implements AccessDecisionManager {
public void decide(Authentication authentication, Object object, ConfigAttributeDefinition config)
throws AccessDeniedException {
throw new UnsupportedOperationException(
"mock method not implemented");
throw new UnsupportedOperationException("mock method not implemented");
}
public boolean supports(Class clazz) {
@@ -459,12 +426,34 @@ public class MethodSecurityInterceptorTests extends TestCase {
}
}
private class MockObjectDefinitionSourceWhichOnlySupportsStrings
extends AbstractMethodDefinitionSource {
private class MockAfterInvocationManagerWhichOnlySupportsStrings implements AfterInvocationManager {
public Object decide(Authentication authentication, Object object, ConfigAttributeDefinition config,
Object returnedObject) throws AccessDeniedException {
throw new UnsupportedOperationException("mock method not implemented");
}
public boolean supports(Class clazz) {
if (String.class.isAssignableFrom(clazz)) {
return true;
} else {
return false;
}
}
public boolean supports(ConfigAttribute attribute) {
return true;
}
}
private class MockObjectDefinitionSourceWhichOnlySupportsStrings extends AbstractMethodDefinitionSource {
public Iterator getConfigAttributeDefinitions() {
return null;
}
protected ConfigAttributeDefinition lookupAttributes(Method method) {
throw new UnsupportedOperationException("mock method not implemented");
}
public boolean supports(Class clazz) {
if (String.class.isAssignableFrom(clazz)) {
return true;
@@ -472,19 +461,11 @@ public class MethodSecurityInterceptorTests extends TestCase {
return false;
}
}
protected ConfigAttributeDefinition lookupAttributes(Method method) {
throw new UnsupportedOperationException(
"mock method not implemented");
}
}
private class MockRunAsManagerWhichOnlySupportsStrings
implements RunAsManager {
public Authentication buildRunAs(Authentication authentication,
Object object, ConfigAttributeDefinition config) {
throw new UnsupportedOperationException(
"mock method not implemented");
private class MockRunAsManagerWhichOnlySupportsStrings implements RunAsManager {
public Authentication buildRunAs(Authentication authentication, Object object, ConfigAttributeDefinition config) {
throw new UnsupportedOperationException("mock method not implemented");
}
public boolean supports(Class clazz) {

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -15,8 +15,6 @@
package org.acegisecurity.intercept.method.aspectj;
import java.lang.reflect.Method;
import junit.framework.TestCase;
import org.acegisecurity.AccessDeniedException;
@@ -28,11 +26,16 @@ import org.acegisecurity.MockAuthenticationManager;
import org.acegisecurity.MockJoinPoint;
import org.acegisecurity.MockRunAsManager;
import org.acegisecurity.TargetObject;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.intercept.method.MethodDefinitionMap;
import org.acegisecurity.intercept.method.MethodDefinitionSourceEditor;
import org.acegisecurity.providers.TestingAuthenticationToken;
import java.lang.reflect.Method;
/**
* Tests {@link AspectJSecurityInterceptor}.
@@ -41,7 +44,7 @@ import org.acegisecurity.providers.TestingAuthenticationToken;
* @version $Id$
*/
public class AspectJSecurityInterceptorTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AspectJSecurityInterceptorTests() {
super();
@@ -51,16 +54,16 @@ public class AspectJSecurityInterceptorTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AspectJSecurityInterceptorTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testCallbackIsInvokedWhenPermissionGranted()
throws Exception {
AspectJSecurityInterceptor si = new AspectJSecurityInterceptor();
@@ -70,8 +73,7 @@ public class AspectJSecurityInterceptorTests extends TestCase {
si.setRunAsManager(new MockRunAsManager());
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
editor.setAsText(
"org.acegisecurity.TargetObject.countLength=MOCK_ONE,MOCK_TWO");
editor.setAsText("org.acegisecurity.TargetObject.countLength=MOCK_ONE,MOCK_TWO");
MethodDefinitionMap map = (MethodDefinitionMap) editor.getValue();
si.setObjectDefinitionSource(map);
@@ -80,14 +82,13 @@ public class AspectJSecurityInterceptorTests extends TestCase {
si.afterPropertiesSet();
Class clazz = TargetObject.class;
Method method = clazz.getMethod("countLength",
new Class[] {String.class});
Method method = clazz.getMethod("countLength", new Class[] {String.class});
MockJoinPoint joinPoint = new MockJoinPoint(new TargetObject(), method);
MockAspectJCallback aspectJCallback = new MockAspectJCallback();
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(
"marissa", "koala",
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("marissa", "koala",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_ONE")}));
Object result = si.invoke(joinPoint, aspectJCallback);
@@ -106,8 +107,7 @@ public class AspectJSecurityInterceptorTests extends TestCase {
si.setRunAsManager(new MockRunAsManager());
MethodDefinitionSourceEditor editor = new MethodDefinitionSourceEditor();
editor.setAsText(
"org.acegisecurity.TargetObject.countLength=MOCK_ONE,MOCK_TWO");
editor.setAsText("org.acegisecurity.TargetObject.countLength=MOCK_ONE,MOCK_TWO");
MethodDefinitionMap map = (MethodDefinitionMap) editor.getValue();
si.setObjectDefinitionSource(map);
@@ -115,15 +115,15 @@ public class AspectJSecurityInterceptorTests extends TestCase {
si.afterPropertiesSet();
Class clazz = TargetObject.class;
Method method = clazz.getMethod("countLength",
new Class[] {String.class});
Method method = clazz.getMethod("countLength", new Class[] {String.class});
MockJoinPoint joinPoint = new MockJoinPoint(new TargetObject(), method);
MockAspectJCallback aspectJCallback = new MockAspectJCallback();
aspectJCallback.setThrowExceptionIfInvoked(true);
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(
"marissa", "koala", new GrantedAuthority[] {}));
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("marissa", "koala",
new GrantedAuthority[] {}));
try {
si.invoke(joinPoint, aspectJCallback);
@@ -135,17 +135,13 @@ public class AspectJSecurityInterceptorTests extends TestCase {
SecurityContextHolder.getContext().setAuthentication(null);
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockAspectJCallback implements AspectJCallback {
private boolean throwExceptionIfInvoked = false;
private MockAspectJCallback() {}
public void setThrowExceptionIfInvoked(boolean throwExceptionIfInvoked) {
this.throwExceptionIfInvoked = throwExceptionIfInvoked;
}
public Object proceedWithObject() {
if (throwExceptionIfInvoked) {
throw new IllegalStateException("AspectJCallback proceeded");
@@ -153,5 +149,9 @@ public class AspectJSecurityInterceptorTests extends TestCase {
return "object proceeded";
}
public void setThrowExceptionIfInvoked(boolean throwExceptionIfInvoked) {
this.throwExceptionIfInvoked = throwExceptionIfInvoked;
}
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -17,8 +17,8 @@ package org.acegisecurity.intercept.web;
import junit.framework.TestCase;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.io.IOException;
@@ -27,10 +27,6 @@ import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
* Tests {@link AbstractFilterInvocationDefinitionSource}.
@@ -39,7 +35,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
* @version $Id$
*/
public class AbstractFilterInvocationDefinitionSourceTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AbstractFilterInvocationDefinitionSourceTests() {
super();
@@ -49,25 +45,23 @@ public class AbstractFilterInvocationDefinitionSourceTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AbstractFilterInvocationDefinitionSourceTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testDoesNotSupportAnotherObject() {
MockFilterInvocationDefinitionSource mfis = new MockFilterInvocationDefinitionSource(false,
true);
MockFilterInvocationDefinitionSource mfis = new MockFilterInvocationDefinitionSource(false, true);
assertFalse(mfis.supports(String.class));
}
public void testGetAttributesForANonFilterInvocation() {
MockFilterInvocationDefinitionSource mfis = new MockFilterInvocationDefinitionSource(false,
true);
MockFilterInvocationDefinitionSource mfis = new MockFilterInvocationDefinitionSource(false, true);
try {
mfis.getAttributes(new String());
@@ -78,8 +72,7 @@ public class AbstractFilterInvocationDefinitionSourceTests extends TestCase {
}
public void testGetAttributesForANullObject() {
MockFilterInvocationDefinitionSource mfis = new MockFilterInvocationDefinitionSource(false,
true);
MockFilterInvocationDefinitionSource mfis = new MockFilterInvocationDefinitionSource(false, true);
try {
mfis.getAttributes(null);
@@ -90,12 +83,10 @@ public class AbstractFilterInvocationDefinitionSourceTests extends TestCase {
}
public void testGetAttributesForFilterInvocationSuccess() {
MockFilterInvocationDefinitionSource mfis = new MockFilterInvocationDefinitionSource(false,
true);
MockFilterInvocationDefinitionSource mfis = new MockFilterInvocationDefinitionSource(false, true);
try {
mfis.getAttributes(new FilterInvocation(
new MockHttpServletRequest(null, null),
mfis.getAttributes(new FilterInvocation(new MockHttpServletRequest(null, null),
new MockHttpServletResponse(), new MockFilterChain()));
fail("Should have thrown UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {
@@ -104,18 +95,16 @@ public class AbstractFilterInvocationDefinitionSourceTests extends TestCase {
}
public void testSupportsFilterInvocation() {
MockFilterInvocationDefinitionSource mfis = new MockFilterInvocationDefinitionSource(false,
true);
MockFilterInvocationDefinitionSource mfis = new MockFilterInvocationDefinitionSource(false, true);
assertTrue(mfis.supports(FilterInvocation.class));
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockFilterChain implements FilterChain {
public void doFilter(ServletRequest arg0, ServletResponse arg1)
throws IOException, ServletException {
throw new UnsupportedOperationException(
"mock method not implemented");
throw new UnsupportedOperationException("mock method not implemented");
}
}
}

View File

@@ -28,14 +28,14 @@ import java.util.Iterator;
/**
* Tests {@link FilterInvocationDefinitionSourceEditor} and its associated
* default {@link RegExpBasedFilterInvocationDefinitionMap}.
* Tests {@link FilterInvocationDefinitionSourceEditor} and its associated default {@link
* RegExpBasedFilterInvocationDefinitionMap}.
*
* @author Ben Alex
* @version $Id$
*/
public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public FilterInvocationDefinitionSourceEditorTests() {
super();
@@ -45,7 +45,7 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(FilterInvocationDefinitionSourceEditorTests.class);
@@ -57,8 +57,7 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
public void testConvertUrlToLowercaseDefaultSettingUnchangedByEditor() {
FilterInvocationDefinitionSourceEditor editor = new FilterInvocationDefinitionSourceEditor();
editor.setAsText(
"\\A/secure/super.*\\Z=ROLE_WE_DONT_HAVE\r\n\\A/secure/.*\\Z=ROLE_SUPERVISOR,ROLE_TELLER");
editor.setAsText("\\A/secure/super.*\\Z=ROLE_WE_DONT_HAVE\r\n\\A/secure/.*\\Z=ROLE_SUPERVISOR,ROLE_TELLER");
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor
.getValue();
@@ -73,8 +72,7 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
"CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON\r\nPATTERN_TYPE_APACHE_ANT\r\n\\/secUre/super/**=ROLE_WE_DONT_HAVE");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(expected.getMessage()
.lastIndexOf("you have specified an uppercase character in line") != -1);
assertTrue(expected.getMessage().lastIndexOf("you have specified an uppercase character in line") != -1);
}
}
@@ -83,18 +81,15 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
editor.setAsText(
"CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON\r\n\\A/secure/super.*\\Z=ROLE_WE_DONT_HAVE\r\n\\A/secure/.*\\Z=ROLE_SUPERVISOR,ROLE_TELLER");
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor
.getValue();
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor.getValue();
assertTrue(map.isConvertUrlToLowercaseBeforeComparison());
}
public void testDefaultIsRegularExpression() {
FilterInvocationDefinitionSourceEditor editor = new FilterInvocationDefinitionSourceEditor();
editor.setAsText(
"\\A/secure/super.*\\Z=ROLE_WE_DONT_HAVE\r\n\\A/secure/.*\\Z=ROLE_SUPERVISOR,ROLE_TELLER");
editor.setAsText("\\A/secure/super.*\\Z=ROLE_WE_DONT_HAVE\r\n\\A/secure/.*\\Z=ROLE_SUPERVISOR,ROLE_TELLER");
FilterInvocationDefinitionMap map = (FilterInvocationDefinitionMap) editor
.getValue();
FilterInvocationDefinitionMap map = (FilterInvocationDefinitionMap) editor.getValue();
assertTrue(map instanceof RegExpBasedFilterInvocationDefinitionMap);
}
@@ -106,8 +101,7 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
"CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON PATTERN_TYPE_APACHE_ANT\r\n\\/secure/super/**=ROLE_WE_DONT_HAVE");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(expected.getMessage()
.lastIndexOf("Line appears to be malformed") != -1);
assertTrue(expected.getMessage().lastIndexOf("Line appears to be malformed") != -1);
}
}
@@ -119,8 +113,7 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
"CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON\r\nPATTERN_TYPE_APACHE_ANT /secure/super/**=ROLE_WE_DONT_HAVE");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(expected.getMessage()
.lastIndexOf("Line appears to be malformed") != -1);
assertTrue(expected.getMessage().lastIndexOf("Line appears to be malformed") != -1);
}
}
@@ -132,8 +125,7 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
"PATTERN_TYPE_APACHE_ANT\r\nCONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON /secure/super/**=ROLE_WE_DONT_HAVE");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(expected.getMessage()
.lastIndexOf("Line appears to be malformed") != -1);
assertTrue(expected.getMessage().lastIndexOf("Line appears to be malformed") != -1);
}
}
@@ -141,8 +133,7 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
FilterInvocationDefinitionSourceEditor editor = new FilterInvocationDefinitionSourceEditor();
editor.setAsText("");
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor
.getValue();
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor.getValue();
assertEquals(0, map.getMapSize());
}
@@ -153,18 +144,15 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
try {
editor.setAsText("*=SOME_ROLE");
} catch (IllegalArgumentException expected) {
assertEquals("Malformed regular expression: *",
expected.getMessage());
assertEquals("Malformed regular expression: *", expected.getMessage());
}
}
public void testIterator() {
FilterInvocationDefinitionSourceEditor editor = new FilterInvocationDefinitionSourceEditor();
editor.setAsText(
"\\A/secure/super.*\\Z=ROLE_WE_DONT_HAVE\r\n\\A/secure/.*\\Z=ROLE_SUPERVISOR,ROLE_TELLER");
editor.setAsText("\\A/secure/super.*\\Z=ROLE_WE_DONT_HAVE\r\n\\A/secure/.*\\Z=ROLE_SUPERVISOR,ROLE_TELLER");
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor
.getValue();
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor.getValue();
Iterator iter = map.getConfigAttributeDefinitions();
int counter = 0;
@@ -180,27 +168,22 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
FilterInvocationDefinitionSourceEditor editor = new FilterInvocationDefinitionSourceEditor();
editor.setAsText("\\A/secure/super.*\\Z=ROLE_WE_DONT_HAVE,ANOTHER_ROLE");
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor
.getValue();
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor.getValue();
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null,
null);
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null, null);
httpRequest.setServletPath("/totally/different/path/index.html");
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(
httpRequest, new MockHttpServletResponse(),
new MockFilterChain()));
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(httpRequest,
new MockHttpServletResponse(), new MockFilterChain()));
assertEquals(null, returned);
}
public void testMultiUrlParsing() {
FilterInvocationDefinitionSourceEditor editor = new FilterInvocationDefinitionSourceEditor();
editor.setAsText(
"\\A/secure/super.*\\Z=ROLE_WE_DONT_HAVE\r\n\\A/secure/.*\\Z=ROLE_SUPERVISOR,ROLE_TELLER");
editor.setAsText("\\A/secure/super.*\\Z=ROLE_WE_DONT_HAVE\r\n\\A/secure/.*\\Z=ROLE_SUPERVISOR,ROLE_TELLER");
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor
.getValue();
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor.getValue();
assertEquals(2, map.getMapSize());
}
@@ -219,8 +202,7 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
FilterInvocationDefinitionSourceEditor editor = new FilterInvocationDefinitionSourceEditor();
editor.setAsText(null);
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor
.getValue();
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor.getValue();
assertEquals(0, map.getMapSize());
}
@@ -229,17 +211,14 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
editor.setAsText(
"\\A/secure/super.*\\Z=ROLE_WE_DONT_HAVE,ANOTHER_ROLE\r\n\\A/secure/.*\\Z=ROLE_SUPERVISOR,ROLE_TELLER");
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor
.getValue();
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor.getValue();
// Test ensures we match the first entry, not the second
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null,
null);
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null, null);
httpRequest.setServletPath("/secure/super/very_secret.html");
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(
httpRequest, new MockHttpServletResponse(),
new MockFilterChain()));
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(httpRequest,
new MockHttpServletResponse(), new MockFilterChain()));
ConfigAttributeDefinition expected = new ConfigAttributeDefinition();
expected.addConfigAttribute(new SecurityConfig("ROLE_WE_DONT_HAVE"));
@@ -253,16 +232,13 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
editor.setAsText(
"\\A/secure/.*\\Z=ROLE_SUPERVISOR,ROLE_TELLER\r\n\\A/secure/super.*\\Z=ROLE_WE_DONT_HAVE,ANOTHER_ROLE");
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor
.getValue();
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor.getValue();
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null,
null);
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null, null);
httpRequest.setServletPath("/secure/super/very_secret.html");
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(
httpRequest, new MockHttpServletResponse(),
new MockFilterChain()));
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(httpRequest,
new MockHttpServletResponse(), new MockFilterChain()));
ConfigAttributeDefinition expected = new ConfigAttributeDefinition();
expected.addConfigAttribute(new SecurityConfig("ROLE_SUPERVISOR"));
@@ -275,16 +251,13 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
FilterInvocationDefinitionSourceEditor editor = new FilterInvocationDefinitionSourceEditor();
editor.setAsText("\\A/secure/super.*\\Z=ROLE_WE_DONT_HAVE,ANOTHER_ROLE");
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor
.getValue();
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor.getValue();
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null,
null);
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null, null);
httpRequest.setServletPath("/secure/super/very_secret.html");
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(
httpRequest, new MockHttpServletResponse(),
new MockFilterChain()));
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(httpRequest,
new MockHttpServletResponse(), new MockFilterChain()));
ConfigAttributeDefinition expected = new ConfigAttributeDefinition();
expected.addConfigAttribute(new SecurityConfig("ROLE_WE_DONT_HAVE"));
@@ -298,8 +271,7 @@ public class FilterInvocationDefinitionSourceEditorTests extends TestCase {
editor.setAsText(
" \\A/secure/super.*\\Z=ROLE_WE_DONT_HAVE,ANOTHER_ROLE \r\n \r\n \r\n // comment line \r\n \\A/testing.*\\Z=ROLE_TEST \r\n");
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor
.getValue();
RegExpBasedFilterInvocationDefinitionMap map = (RegExpBasedFilterInvocationDefinitionMap) editor.getValue();
assertEquals(2, map.getMapSize());
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -19,26 +19,23 @@ import junit.framework.TestCase;
import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.MockFilterChain;
import org.acegisecurity.SecurityConfig;
import java.util.Iterator;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.util.Iterator;
/**
* Tests {@link FilterInvocationDefinitionSourceEditor} and its associated
* {@link PathBasedFilterInvocationDefinitionMap}.
* Tests {@link FilterInvocationDefinitionSourceEditor} and its associated {@link
* PathBasedFilterInvocationDefinitionMap}.
*
* @author Ben Alex
* @version $Id$
*/
public class FilterInvocationDefinitionSourceEditorWithPathsTests
extends TestCase {
//~ Constructors ===========================================================
public class FilterInvocationDefinitionSourceEditorWithPathsTests extends TestCase {
//~ Constructors ===================================================================================================
public FilterInvocationDefinitionSourceEditorWithPathsTests() {
super();
@@ -48,23 +45,22 @@ public class FilterInvocationDefinitionSourceEditorWithPathsTests
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(FilterInvocationDefinitionSourceEditorWithPathsTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAntPathDirectiveIsDetected() {
FilterInvocationDefinitionSourceEditor editor = new FilterInvocationDefinitionSourceEditor();
editor.setAsText(
"PATTERN_TYPE_APACHE_ANT\r\n/secure/super/*=ROLE_WE_DONT_HAVE\r\n/secure/*=ROLE_SUPERVISOR,ROLE_TELLER");
FilterInvocationDefinitionMap map = (FilterInvocationDefinitionMap) editor
.getValue();
FilterInvocationDefinitionMap map = (FilterInvocationDefinitionMap) editor.getValue();
assertTrue(map instanceof PathBasedFilterInvocationDefinitionMap);
}
@@ -73,8 +69,7 @@ public class FilterInvocationDefinitionSourceEditorWithPathsTests
editor.setAsText(
"PATTERN_TYPE_APACHE_ANT\r\n/secure/super/*=ROLE_WE_DONT_HAVE\r\n/secure/*=ROLE_SUPERVISOR,ROLE_TELLER");
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor
.getValue();
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor.getValue();
assertFalse(map.isConvertUrlToLowercaseBeforeComparison());
}
@@ -83,18 +78,26 @@ public class FilterInvocationDefinitionSourceEditorWithPathsTests
editor.setAsText(
"CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON\r\nPATTERN_TYPE_APACHE_ANT\r\n/secure/super/*=ROLE_WE_DONT_HAVE\r\n/secure/*=ROLE_SUPERVISOR,ROLE_TELLER");
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor
.getValue();
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor.getValue();
assertTrue(map.isConvertUrlToLowercaseBeforeComparison());
}
public void testInvalidNameValueFailsToParse() {
FilterInvocationDefinitionSourceEditor editor = new FilterInvocationDefinitionSourceEditor();
try {
// Use a "==" instead of an "="
editor.setAsText(" PATTERN_TYPE_APACHE_ANT\r\n /secure/*==ROLE_SUPERVISOR,ROLE_TELLER \r\n");
fail("Shouldn't be able to use '==' for config attribute.");
} catch (IllegalArgumentException expected) {}
}
public void testIterator() {
FilterInvocationDefinitionSourceEditor editor = new FilterInvocationDefinitionSourceEditor();
editor.setAsText(
"PATTERN_TYPE_APACHE_ANT\r\n/secure/super/*=ROLE_WE_DONT_HAVE\r\n/secure/*=ROLE_SUPERVISOR,ROLE_TELLER");
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor
.getValue();
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor.getValue();
Iterator iter = map.getConfigAttributeDefinitions();
int counter = 0;
@@ -108,19 +111,15 @@ public class FilterInvocationDefinitionSourceEditorWithPathsTests
public void testMapReturnsNullWhenNoMatchFound() throws Exception {
FilterInvocationDefinitionSourceEditor editor = new FilterInvocationDefinitionSourceEditor();
editor.setAsText(
"PATTERN_TYPE_APACHE_ANT\r\n/secure/super/*=ROLE_WE_DONT_HAVE");
editor.setAsText("PATTERN_TYPE_APACHE_ANT\r\n/secure/super/*=ROLE_WE_DONT_HAVE");
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor
.getValue();
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor.getValue();
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null,
null);
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null, null);
httpRequest.setServletPath("/totally/different/path/index.html");
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(
httpRequest, new MockHttpServletResponse(),
new MockFilterChain()));
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(httpRequest,
new MockHttpServletResponse(), new MockFilterChain()));
assertEquals(null, returned);
}
@@ -130,8 +129,7 @@ public class FilterInvocationDefinitionSourceEditorWithPathsTests
editor.setAsText(
"PATTERN_TYPE_APACHE_ANT\r\n/secure/super/*=ROLE_WE_DONT_HAVE\r\n/secure/*=ROLE_SUPERVISOR,ROLE_TELLER");
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor
.getValue();
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor.getValue();
assertEquals(2, map.getMapSize());
}
@@ -139,7 +137,7 @@ public class FilterInvocationDefinitionSourceEditorWithPathsTests
Class clazz = PathBasedFilterInvocationDefinitionMap.EntryHolder.class;
try {
clazz.getDeclaredConstructor((Class[])null);
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
} catch (NoSuchMethodException expected) {
assertTrue(true);
@@ -151,17 +149,14 @@ public class FilterInvocationDefinitionSourceEditorWithPathsTests
editor.setAsText(
"PATTERN_TYPE_APACHE_ANT\r\n/secure/super/**=ROLE_WE_DONT_HAVE,ANOTHER_ROLE\r\n/secure/**=ROLE_SUPERVISOR,ROLE_TELLER");
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor
.getValue();
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor.getValue();
// Test ensures we match the first entry, not the second
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null,
null);
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null, null);
httpRequest.setServletPath("/secure/super/very_secret.html");
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(
httpRequest, new MockHttpServletResponse(),
new MockFilterChain()));
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(httpRequest,
new MockHttpServletResponse(), new MockFilterChain()));
ConfigAttributeDefinition expected = new ConfigAttributeDefinition();
expected.addConfigAttribute(new SecurityConfig("ROLE_WE_DONT_HAVE"));
@@ -175,16 +170,13 @@ public class FilterInvocationDefinitionSourceEditorWithPathsTests
editor.setAsText(
"PATTERN_TYPE_APACHE_ANT\r\n/secure/**=ROLE_SUPERVISOR,ROLE_TELLER\r\n/secure/super/**=ROLE_WE_DONT_HAVE");
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor
.getValue();
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor.getValue();
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null,
null);
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null, null);
httpRequest.setServletPath("/secure/super/very_secret.html");
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(
httpRequest, new MockHttpServletResponse(),
new MockFilterChain()));
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(httpRequest,
new MockHttpServletResponse(), new MockFilterChain()));
ConfigAttributeDefinition expected = new ConfigAttributeDefinition();
expected.addConfigAttribute(new SecurityConfig("ROLE_SUPERVISOR"));
@@ -195,19 +187,15 @@ public class FilterInvocationDefinitionSourceEditorWithPathsTests
public void testSingleUrlParsing() throws Exception {
FilterInvocationDefinitionSourceEditor editor = new FilterInvocationDefinitionSourceEditor();
editor.setAsText(
"PATTERN_TYPE_APACHE_ANT\r\n/secure/super/*=ROLE_WE_DONT_HAVE,ANOTHER_ROLE");
editor.setAsText("PATTERN_TYPE_APACHE_ANT\r\n/secure/super/*=ROLE_WE_DONT_HAVE,ANOTHER_ROLE");
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor
.getValue();
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor.getValue();
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null,
null);
MockHttpServletRequest httpRequest = new MockHttpServletRequest(null, null);
httpRequest.setServletPath("/secure/super/very_secret.html");
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(
httpRequest, new MockHttpServletResponse(),
new MockFilterChain()));
ConfigAttributeDefinition returned = map.getAttributes(new FilterInvocation(httpRequest,
new MockHttpServletResponse(), new MockFilterChain()));
ConfigAttributeDefinition expected = new ConfigAttributeDefinition();
expected.addConfigAttribute(new SecurityConfig("ROLE_WE_DONT_HAVE"));
@@ -221,18 +209,7 @@ public class FilterInvocationDefinitionSourceEditorWithPathsTests
editor.setAsText(
" PATTERN_TYPE_APACHE_ANT\r\n /secure/super/*=ROLE_WE_DONT_HAVE\r\n /secure/*=ROLE_SUPERVISOR,ROLE_TELLER \r\n \r\n \r\n // comment line \r\n \r\n");
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor
.getValue();
PathBasedFilterInvocationDefinitionMap map = (PathBasedFilterInvocationDefinitionMap) editor.getValue();
assertEquals(2, map.getMapSize());
}
public void testInvalidNameValueFailsToParse() {
FilterInvocationDefinitionSourceEditor editor = new FilterInvocationDefinitionSourceEditor();
try {
// Use a "==" instead of an "="
editor.setAsText(" PATTERN_TYPE_APACHE_ANT\r\n /secure/*==ROLE_SUPERVISOR,ROLE_TELLER \r\n");
fail("Shouldn't be able to use '==' for config attribute.");
} catch(IllegalArgumentException expected) {
}
}
}

View File

@@ -34,7 +34,7 @@ import javax.servlet.ServletResponse;
* @version $Id$
*/
public class FilterInvocationTests extends MockObjectTestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public FilterInvocationTests() {
super();
@@ -44,7 +44,7 @@ public class FilterInvocationTests extends MockObjectTestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(FilterInvocationTests.class);
@@ -73,10 +73,8 @@ public class FilterInvocationTests extends MockObjectTestCase {
assertEquals(response, fi.getHttpResponse());
assertEquals(chain, fi.getChain());
assertEquals("/HelloWorld/some/more/segments.html", fi.getRequestUrl());
assertEquals("FilterInvocation: URL: /HelloWorld/some/more/segments.html",
fi.toString());
assertEquals("http://www.example.com/mycontext/HelloWorld/some/more/segments.html",
fi.getFullRequestUrl());
assertEquals("FilterInvocation: URL: /HelloWorld/some/more/segments.html", fi.toString());
assertEquals("http://www.example.com/mycontext/HelloWorld/some/more/segments.html", fi.getFullRequestUrl());
}
public void testNoArgConstructorDoesntExist() {
@@ -135,8 +133,7 @@ public class FilterInvocationTests extends MockObjectTestCase {
new FilterInvocation(request, response, chain);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("Can only process HttpServletRequest",
expected.getMessage());
assertEquals("Can only process HttpServletRequest", expected.getMessage());
}
}
@@ -149,8 +146,7 @@ public class FilterInvocationTests extends MockObjectTestCase {
new FilterInvocation(request, response, chain);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("Can only process HttpServletResponse",
expected.getMessage());
assertEquals("Can only process HttpServletResponse", expected.getMessage());
}
}
@@ -169,8 +165,7 @@ public class FilterInvocationTests extends MockObjectTestCase {
FilterInvocation fi = new FilterInvocation(request, response, chain);
assertEquals("/HelloWorld?foo=bar", fi.getRequestUrl());
assertEquals("FilterInvocation: URL: /HelloWorld?foo=bar", fi.toString());
assertEquals("http://www.example.com/mycontext/HelloWorld?foo=bar",
fi.getFullRequestUrl());
assertEquals("http://www.example.com/mycontext/HelloWorld?foo=bar", fi.getFullRequestUrl());
}
public void testStringMethodsWithoutAnyQueryString() {
@@ -187,7 +182,6 @@ public class FilterInvocationTests extends MockObjectTestCase {
FilterInvocation fi = new FilterInvocation(request, response, chain);
assertEquals("/HelloWorld", fi.getRequestUrl());
assertEquals("FilterInvocation: URL: /HelloWorld", fi.toString());
assertEquals("http://www.example.com/mycontext/HelloWorld",
fi.getFullRequestUrl());
assertEquals("http://www.example.com/mycontext/HelloWorld", fi.getFullRequestUrl());
}
}

View File

@@ -55,7 +55,7 @@ import javax.servlet.ServletResponse;
* @version $Id$
*/
public class FilterSecurityInterceptorTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public FilterSecurityInterceptorTests() {
super();
@@ -65,7 +65,7 @@ public class FilterSecurityInterceptorTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(FilterSecurityInterceptorTests.class);
@@ -91,11 +91,9 @@ public class FilterSecurityInterceptorTests extends TestCase {
return true;
}
public void decide(Authentication authentication,
Object object, ConfigAttributeDefinition config)
public void decide(Authentication authentication, Object object, ConfigAttributeDefinition config)
throws AccessDeniedException {
throw new UnsupportedOperationException(
"mock method not implemented");
throw new UnsupportedOperationException("mock method not implemented");
}
});
@@ -124,11 +122,9 @@ public class FilterSecurityInterceptorTests extends TestCase {
return true;
}
public Authentication buildRunAs(
Authentication authentication, Object object,
public Authentication buildRunAs(Authentication authentication, Object object,
ConfigAttributeDefinition config) {
throw new UnsupportedOperationException(
"mock method not implemented");
throw new UnsupportedOperationException("mock method not implemented");
}
});
@@ -148,15 +144,13 @@ public class FilterSecurityInterceptorTests extends TestCase {
interceptor.setAccessDecisionManager(new MockAccessDecisionManager());
interceptor.setAuthenticationManager(new MockAuthenticationManager());
interceptor.setRunAsManager(new MockRunAsManager());
interceptor.setApplicationEventPublisher(MockApplicationContext
.getContext());
interceptor.setApplicationEventPublisher(MockApplicationContext.getContext());
// Setup a mock config attribute definition
ConfigAttributeDefinition def = new ConfigAttributeDefinition();
def.addConfigAttribute(new SecurityConfig("MOCK_OK"));
MockFilterInvocationDefinitionMap mockSource = new MockFilterInvocationDefinitionMap("/secure/page.html",
def);
MockFilterInvocationDefinitionMap mockSource = new MockFilterInvocationDefinitionMap("/secure/page.html", def);
interceptor.setObjectDefinitionSource(mockSource);
// Setup our expectation that the filter chain will be invoked, as access is granted
@@ -170,8 +164,7 @@ public class FilterSecurityInterceptorTests extends TestCase {
request.setServerPort(443);
// Setup a Context
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_OK")});
SecurityContextHolder.getContext().setAuthentication(token);
@@ -197,9 +190,8 @@ public class FilterSecurityInterceptorTests extends TestCase {
}
/**
* We just test invocation works in a success event. There is no need to
* test access denied events as the abstract parent enforces that logic,
* which is extensively tested separately.
* We just test invocation works in a success event. There is no need to test access denied events as the
* abstract parent enforces that logic, which is extensively tested separately.
*
* @throws Throwable DOCUMENT ME!
*/
@@ -209,15 +201,13 @@ public class FilterSecurityInterceptorTests extends TestCase {
interceptor.setAccessDecisionManager(new MockAccessDecisionManager());
interceptor.setAuthenticationManager(new MockAuthenticationManager());
interceptor.setRunAsManager(new MockRunAsManager());
interceptor.setApplicationEventPublisher(MockApplicationContext
.getContext());
interceptor.setApplicationEventPublisher(MockApplicationContext.getContext());
// Setup a mock config attribute definition
ConfigAttributeDefinition def = new ConfigAttributeDefinition();
def.addConfigAttribute(new SecurityConfig("MOCK_OK"));
MockFilterInvocationDefinitionMap mockSource = new MockFilterInvocationDefinitionMap("/secure/page.html",
def);
MockFilterInvocationDefinitionMap mockSource = new MockFilterInvocationDefinitionMap("/secure/page.html", def);
interceptor.setObjectDefinitionSource(mockSource);
// Setup our expectation that the filter chain will be invoked, as access is granted
@@ -229,8 +219,7 @@ public class FilterSecurityInterceptorTests extends TestCase {
request.setServletPath("/secure/page.html");
// Setup a Context
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_OK")});
SecurityContextHolder.getContext().setAuthentication(token);
@@ -242,7 +231,7 @@ public class FilterSecurityInterceptorTests extends TestCase {
SecurityContextHolder.clearContext();
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockFilterChain implements FilterChain {
private boolean expectToProceed;
@@ -265,13 +254,11 @@ public class FilterSecurityInterceptorTests extends TestCase {
}
}
private class MockFilterInvocationDefinitionMap
implements FilterInvocationDefinitionSource {
private class MockFilterInvocationDefinitionMap implements FilterInvocationDefinitionSource {
private ConfigAttributeDefinition toReturn;
private String servletPath;
public MockFilterInvocationDefinitionMap(String servletPath,
ConfigAttributeDefinition toReturn) {
public MockFilterInvocationDefinitionMap(String servletPath, ConfigAttributeDefinition toReturn) {
this.servletPath = servletPath;
this.toReturn = toReturn;
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -29,17 +29,15 @@ import java.util.Vector;
* @author Ben Alex
* @version $Id$
*/
public class MockFilterInvocationDefinitionSource
extends AbstractFilterInvocationDefinitionSource {
//~ Instance fields ========================================================
public class MockFilterInvocationDefinitionSource extends AbstractFilterInvocationDefinitionSource {
//~ Instance fields ================================================================================================
private List list;
private boolean returnAnIterator;
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public MockFilterInvocationDefinitionSource(
boolean includeInvalidAttributes, boolean returnAnIteratorWhenRequested) {
public MockFilterInvocationDefinitionSource(boolean includeInvalidAttributes, boolean returnAnIteratorWhenRequested) {
returnAnIterator = returnAnIteratorWhenRequested;
list = new Vector();
@@ -71,7 +69,7 @@ public class MockFilterInvocationDefinitionSource
super();
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public Iterator getConfigAttributeDefinitions() {
if (returnAnIterator) {

View File

@@ -26,14 +26,14 @@ import org.springframework.mock.web.MockHttpServletResponse;
/**
* Tests parts of {@link PathBasedFilterInvocationDefinitionMap} not tested by
* {@link FilterInvocationDefinitionSourceEditorWithPathsTests}.
* Tests parts of {@link PathBasedFilterInvocationDefinitionMap} not tested by {@link
* FilterInvocationDefinitionSourceEditorWithPathsTests}.
*
* @author Ben Alex
* @version $Id$
*/
public class PathBasedFilterDefinitionMapTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public PathBasedFilterDefinitionMapTests() {
super();
@@ -43,7 +43,7 @@ public class PathBasedFilterDefinitionMapTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(PathBasedFilterDefinitionMapTests.class);
@@ -80,11 +80,9 @@ public class PathBasedFilterDefinitionMapTests extends TestCase {
MockHttpServletRequest req = request;
req.setServletPath("/SeCuRE/super/somefile.html");
FilterInvocation fi = new FilterInvocation(req,
new MockHttpServletResponse(), new MockFilterChain());
FilterInvocation fi = new FilterInvocation(req, new MockHttpServletResponse(), new MockFilterChain());
ConfigAttributeDefinition response = map.lookupAttributes(fi
.getRequestUrl());
ConfigAttributeDefinition response = map.lookupAttributes(fi.getRequestUrl());
assertEquals(def, response);
}
@@ -103,11 +101,9 @@ public class PathBasedFilterDefinitionMapTests extends TestCase {
MockHttpServletRequest req = request;
req.setServletPath("/SeCuRE/super/somefile.html");
FilterInvocation fi = new FilterInvocation(req,
new MockHttpServletResponse(), new MockFilterChain());
FilterInvocation fi = new FilterInvocation(req, new MockHttpServletResponse(), new MockFilterChain());
ConfigAttributeDefinition response = map.lookupAttributes(fi
.getRequestUrl());
ConfigAttributeDefinition response = map.lookupAttributes(fi.getRequestUrl());
assertEquals(null, response);
}
@@ -126,11 +122,9 @@ public class PathBasedFilterDefinitionMapTests extends TestCase {
MockHttpServletRequest req = request;
req.setServletPath("/secure/super/somefile.html");
FilterInvocation fi = new FilterInvocation(req,
new MockHttpServletResponse(), new MockFilterChain());
FilterInvocation fi = new FilterInvocation(req, new MockHttpServletResponse(), new MockFilterChain());
ConfigAttributeDefinition response = map.lookupAttributes(fi
.getRequestUrl());
ConfigAttributeDefinition response = map.lookupAttributes(fi.getRequestUrl());
assertEquals(def, response);
}
@@ -149,11 +143,9 @@ public class PathBasedFilterDefinitionMapTests extends TestCase {
MockHttpServletRequest req = request;
req.setServletPath("/someAdminPage.html?a=/test");
FilterInvocation fi = new FilterInvocation(req,
new MockHttpServletResponse(), new MockFilterChain());
FilterInvocation fi = new FilterInvocation(req, new MockHttpServletResponse(), new MockFilterChain());
ConfigAttributeDefinition response = map.lookupAttributes(fi
.getRequestUrl());
ConfigAttributeDefinition response = map.lookupAttributes(fi.getRequestUrl());
assertEquals(def, response); // see SEC-161 (it should truncate after ? sign)
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -19,8 +19,6 @@ import junit.framework.TestCase;
import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.MockFilterChain;
import org.acegisecurity.SecurityConfig;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -28,14 +26,14 @@ import org.springframework.mock.web.MockHttpServletResponse;
/**
* Tests parts of {@link RegExpBasedFilterInvocationDefinitionMap} not tested
* by {@link FilterInvocationDefinitionSourceEditorTests}.
* Tests parts of {@link RegExpBasedFilterInvocationDefinitionMap} not tested by {@link
* FilterInvocationDefinitionSourceEditorTests}.
*
* @author Ben Alex
* @version $Id$
*/
public class RegExpBasedFilterDefinitionMapTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public RegExpBasedFilterDefinitionMapTests() {
super();
@@ -45,16 +43,16 @@ public class RegExpBasedFilterDefinitionMapTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(RegExpBasedFilterDefinitionMapTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testConvertUrlToLowercaseIsFalseByDefault() {
RegExpBasedFilterInvocationDefinitionMap map = new RegExpBasedFilterInvocationDefinitionMap();
assertFalse(map.isConvertUrlToLowercaseBeforeComparison());
@@ -78,14 +76,13 @@ public class RegExpBasedFilterDefinitionMapTests extends TestCase {
// Build a HTTP request
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI(null);
MockHttpServletRequest req = request;
req.setServletPath("/SeCuRE/super/somefile.html");
FilterInvocation fi = new FilterInvocation(req,
new MockHttpServletResponse(), new MockFilterChain());
FilterInvocation fi = new FilterInvocation(req, new MockHttpServletResponse(), new MockFilterChain());
ConfigAttributeDefinition response = map.lookupAttributes(fi
.getRequestUrl());
ConfigAttributeDefinition response = map.lookupAttributes(fi.getRequestUrl());
assertEquals(def, response);
}
@@ -100,14 +97,13 @@ public class RegExpBasedFilterDefinitionMapTests extends TestCase {
// Build a HTTP request
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI(null);
MockHttpServletRequest req = request;
req.setServletPath("/SeCuRE/super/somefile.html");
FilterInvocation fi = new FilterInvocation(req,
new MockHttpServletResponse(), new MockFilterChain());
FilterInvocation fi = new FilterInvocation(req, new MockHttpServletResponse(), new MockFilterChain());
ConfigAttributeDefinition response = map.lookupAttributes(fi
.getRequestUrl());
ConfigAttributeDefinition response = map.lookupAttributes(fi.getRequestUrl());
assertEquals(null, response);
}
@@ -122,14 +118,13 @@ public class RegExpBasedFilterDefinitionMapTests extends TestCase {
// Build a HTTP request
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI(null);
MockHttpServletRequest req = request;
req.setServletPath("/secure/super/somefile.html");
FilterInvocation fi = new FilterInvocation(req,
new MockHttpServletResponse(), new MockFilterChain());
FilterInvocation fi = new FilterInvocation(req, new MockHttpServletResponse(), new MockFilterChain());
ConfigAttributeDefinition response = map.lookupAttributes(fi
.getRequestUrl());
ConfigAttributeDefinition response = map.lookupAttributes(fi.getRequestUrl());
assertEquals(def, response);
}
}

View File

@@ -29,14 +29,13 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Tests {@link
* org.acegisecurity.intercept.web.WebInvocationPrivilegeEvaluator}.
* Tests {@link org.acegisecurity.intercept.web.WebInvocationPrivilegeEvaluator}.
*
* @author Ben Alex
* @version $Id$
*/
public class WebInvocationPrivilegeEvaluatorTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public WebInvocationPrivilegeEvaluatorTests() {
super();
@@ -46,7 +45,7 @@ public class WebInvocationPrivilegeEvaluatorTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(WebInvocationPrivilegeEvaluatorTests.class);
@@ -56,13 +55,11 @@ public class WebInvocationPrivilegeEvaluatorTests extends TestCase {
ApplicationContext context = new ClassPathXmlApplicationContext(
"org/acegisecurity/intercept/web/applicationContext.xml");
return (FilterSecurityInterceptor) context.getBean(
"securityInterceptor");
return (FilterSecurityInterceptor) context.getBean("securityInterceptor");
}
public void testAllowsAccess1() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_INDEX")});
FilterInvocation fi = FilterInvocationUtils.create("/foo/index.jsp");
FilterSecurityInterceptor interceptor = makeFilterSecurityInterceptor();
@@ -75,8 +72,7 @@ public class WebInvocationPrivilegeEvaluatorTests extends TestCase {
}
public void testAllowsAccess2() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_USER")});
FilterInvocation fi = FilterInvocationUtils.create("/anything.jsp");
FilterSecurityInterceptor interceptor = makeFilterSecurityInterceptor();
@@ -89,8 +85,7 @@ public class WebInvocationPrivilegeEvaluatorTests extends TestCase {
}
public void testDeniesAccess1() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_NOTHING_USEFUL")});
FilterInvocation fi = FilterInvocationUtils.create("/anything.jsp");
FilterSecurityInterceptor interceptor = makeFilterSecurityInterceptor();

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -17,15 +17,21 @@ package org.acegisecurity.ldap;
import junit.framework.TestCase;
import java.util.Hashtable;
import org.apache.directory.server.core.jndi.CoreContextFactory;
import java.util.Hashtable;
/**
*
DOCUMENT ME!
*
* @author Luke Taylor
* @version $Id$
*/
public abstract class AbstractLdapServerTestCase extends TestCase {
//~ Static fields/initializers =====================================================================================
private static final String ROOT_DN = "dc=acegisecurity,dc=org";
protected static final String MANAGER_USER = "cn=manager," + ROOT_DN;
protected static final String MANAGER_PASSWORD = "acegisecurity";
@@ -35,21 +41,31 @@ public abstract class AbstractLdapServerTestCase extends TestCase {
// private static final String CONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
// private static final Hashtable EXTRA_ENV = new Hashtable();
// Embedded (non-networked) server config
private static final LdapTestServer SERVER = new LdapTestServer();
private static final String PROVIDER_URL = ROOT_DN;
private static final String CONTEXT_FACTORY = CoreContextFactory.class.getName();
private static final Hashtable EXTRA_ENV = SERVER.getConfiguration().toJndiEnvironment();
protected AbstractLdapServerTestCase() {
}
//~ Instance fields ================================================================================================
private DefaultInitialDirContextFactory idf;
//~ Constructors ===================================================================================================
protected AbstractLdapServerTestCase() {}
protected AbstractLdapServerTestCase(String string) {
super(string);
}
private DefaultInitialDirContextFactory idf;
//~ Methods ========================================================================================================
protected DefaultInitialDirContextFactory getInitialCtxFactory() {
return idf;
}
protected void onSetUp() {}
public final void setUp() {
idf = new DefaultInitialDirContextFactory(PROVIDER_URL);
@@ -58,10 +74,4 @@ public abstract class AbstractLdapServerTestCase extends TestCase {
onSetUp();
}
protected void onSetUp() {}
protected DefaultInitialDirContextFactory getInitialCtxFactory() {
return idf;
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -15,12 +15,14 @@
package org.acegisecurity.ldap;
import javax.naming.Context;
import javax.naming.directory.DirContext;
import org.acegisecurity.AcegiMessageSource;
import org.acegisecurity.BadCredentialsException;
import java.util.Hashtable;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.AcegiMessageSource;
import javax.naming.Context;
import javax.naming.directory.DirContext;
/**
* Tests {@link org.acegisecurity.ldap.DefaultInitialDirContextFactory}.
@@ -29,52 +31,17 @@ import org.acegisecurity.AcegiMessageSource;
* @version $Id$
*/
public class DefaultInitialDirContextFactoryTests extends AbstractLdapServerTestCase {
//~ Instance fields ================================================================================================
DefaultInitialDirContextFactory idf;
//~ Methods ========================================================================================================
public void onSetUp() {
idf = getInitialCtxFactory();
idf.setMessageSource(new AcegiMessageSource());
}
// public void testNonLdapUrlIsRejected() throws Exception {
// DefaultInitialDirContextFactory idf = new DefaultInitialDirContextFactory();
//
// idf.setUrl("http://acegisecurity.org/dc=acegisecurity,dc=org");
// idf.setInitialContextFactory(CoreContextFactory.class.getName());
//
// try {
// idf.afterPropertiesSet();
// fail("Expected exception for non 'ldap://' URL");
// } catch(IllegalArgumentException expected) {
// }
// }
public void testServiceLocationUrlIsSupported() {
idf = new DefaultInitialDirContextFactory("ldap:///dc=acegisecurity,dc=org");
assertEquals("dc=acegisecurity,dc=org", idf.getRootDn());
}
public void testSecureLdapUrlIsSupported() {
idf = new DefaultInitialDirContextFactory("ldaps://localhost/dc=acegisecurity,dc=org");
assertEquals("dc=acegisecurity,dc=org", idf.getRootDn());
}
public void testConnectionFailure() throws Exception {
// Use the wrong port
idf = new DefaultInitialDirContextFactory("ldap://localhost:60389");
idf.setInitialContextFactory("com.sun.jndi.ldap.LdapCtxFactory");
Hashtable env = new Hashtable();
env.put("com.sun.jndi.ldap.connect.timeout", "200");
idf.setExtraEnvVars(env);
idf.setUseConnectionPool(false); // coverage purposes only
try {
idf.newInitialDirContext();
fail("Connection succeeded unexpectedly");
} catch(LdapDataAccessException expected) {
}
}
public void testAnonymousBindSucceeds() throws Exception {
DirContext ctx = idf.newInitialDirContext();
// Connection pooling should be set by default for anon users.
@@ -83,6 +50,36 @@ public class DefaultInitialDirContextFactoryTests extends AbstractLdapServerTest
ctx.close();
}
public void testBaseDnIsParsedFromCorrectlyFromUrl() {
idf = new DefaultInitialDirContextFactory("ldap://acegisecurity.org/dc=acegisecurity,dc=org");
assertEquals("dc=acegisecurity,dc=org", idf.getRootDn());
// Check with an empty root
idf = new DefaultInitialDirContextFactory("ldap://acegisecurity.org/");
assertEquals("", idf.getRootDn());
// Empty root without trailing slash
idf = new DefaultInitialDirContextFactory("ldap://acegisecurity.org");
assertEquals("", idf.getRootDn());
}
public void testBindAsManagerFailsIfNoPasswordSet()
throws Exception {
idf.setManagerDn(MANAGER_USER);
DirContext ctx = null;
try {
ctx = idf.newInitialDirContext();
fail("Binding with no manager password should fail.");
// Can't rely on this property being there with embedded server
// assertEquals("true",ctx.getEnvironment().get("com.sun.jndi.ldap.connect.pool"));
} catch (BadCredentialsException expected) {}
LdapUtils.closeContext(ctx);
}
public void testBindAsManagerSucceeds() throws Exception {
idf.setManagerPassword(MANAGER_PASSWORD);
idf.setManagerDn(MANAGER_USER);
@@ -93,45 +90,31 @@ public class DefaultInitialDirContextFactoryTests extends AbstractLdapServerTest
ctx.close();
}
public void testBindAsManagerFailsIfNoPasswordSet() throws Exception {
idf.setManagerDn(MANAGER_USER);
DirContext ctx = null;
try {
ctx = idf.newInitialDirContext();
fail("Binding with no manager password should fail.");
// Can't rely on this property being there with embedded server
// assertEquals("true",ctx.getEnvironment().get("com.sun.jndi.ldap.connect.pool"));
} catch(BadCredentialsException expected) {
}
LdapUtils.closeContext(ctx);
}
public void testInvalidPasswordCausesBadCredentialsException() throws Exception {
idf.setManagerDn(MANAGER_USER);
idf.setManagerPassword("wrongpassword");
DirContext ctx = null;
try {
ctx = idf.newInitialDirContext();
fail("Binding with wrong credentials should fail.");
} catch(BadCredentialsException expected) {
}
LdapUtils.closeContext(ctx);
}
public void testConnectionAsSpecificUserSucceeds() throws Exception {
DirContext ctx = idf.newInitialDirContext("uid=Bob,ou=people,dc=acegisecurity,dc=org",
"bobspassword");
public void testConnectionAsSpecificUserSucceeds()
throws Exception {
DirContext ctx = idf.newInitialDirContext("uid=Bob,ou=people,dc=acegisecurity,dc=org", "bobspassword");
// We don't want pooling for specific users.
// assertNull(ctx.getEnvironment().get("com.sun.jndi.ldap.connect.pool"));
// com.sun.jndi.ldap.LdapPoolManager.showStats(System.out);
ctx.close();
}
public void testConnectionFailure() throws Exception {
// Use the wrong port
idf = new DefaultInitialDirContextFactory("ldap://localhost:60389");
idf.setInitialContextFactory("com.sun.jndi.ldap.LdapCtxFactory");
Hashtable env = new Hashtable();
env.put("com.sun.jndi.ldap.connect.timeout", "200");
idf.setExtraEnvVars(env);
idf.setUseConnectionPool(false); // coverage purposes only
try {
idf.newInitialDirContext();
fail("Connection succeeded unexpectedly");
} catch (LdapDataAccessException expected) {}
}
public void testEnvironment() {
idf = new DefaultInitialDirContextFactory("ldap://acegisecurity.org/");
@@ -139,7 +122,7 @@ public class DefaultInitialDirContextFactoryTests extends AbstractLdapServerTest
Hashtable env = idf.getEnvironment();
//assertEquals("com.sun.jndi.ldap.LdapCtxFactory", env.get(Context.INITIAL_CONTEXT_FACTORY));
assertEquals("ldap://acegisecurity.org/", env.get(Context.PROVIDER_URL));
assertEquals("simple",env.get(Context.SECURITY_AUTHENTICATION));
assertEquals("simple", env.get(Context.SECURITY_AUTHENTICATION));
assertNull(env.get(Context.SECURITY_PRINCIPAL));
assertNull(env.get(Context.SECURITY_CREDENTIALS));
@@ -161,30 +144,53 @@ public class DefaultInitialDirContextFactoryTests extends AbstractLdapServerTest
assertEquals("extravarvalue", env.get("extravar"));
}
public void testBaseDnIsParsedFromCorrectlyFromUrl() {
idf = new DefaultInitialDirContextFactory("ldap://acegisecurity.org/dc=acegisecurity,dc=org");
assertEquals("dc=acegisecurity,dc=org", idf.getRootDn());
public void testInvalidPasswordCausesBadCredentialsException()
throws Exception {
idf.setManagerDn(MANAGER_USER);
idf.setManagerPassword("wrongpassword");
// Check with an empty root
idf = new DefaultInitialDirContextFactory("ldap://acegisecurity.org/");
assertEquals("", idf.getRootDn());
DirContext ctx = null;
// Empty root without trailing slash
idf = new DefaultInitialDirContextFactory("ldap://acegisecurity.org");
assertEquals("", idf.getRootDn());
try {
ctx = idf.newInitialDirContext();
fail("Binding with wrong credentials should fail.");
} catch (BadCredentialsException expected) {}
LdapUtils.closeContext(ctx);
}
public void testMultipleProviderUrlsAreAccepted() {
idf = new DefaultInitialDirContextFactory("ldaps://acegisecurity.org/dc=acegisecurity,dc=org " +
"ldap://monkeymachine.co.uk/dc=acegisecurity,dc=org");
idf = new DefaultInitialDirContextFactory("ldaps://acegisecurity.org/dc=acegisecurity,dc=org "
+ "ldap://monkeymachine.co.uk/dc=acegisecurity,dc=org");
}
public void testMultipleProviderUrlsWithDifferentRootsAreRejected() {
try {
idf = new DefaultInitialDirContextFactory("ldap://acegisecurity.org/dc=acegisecurity,dc=org " +
"ldap://monkeymachine.co.uk/dc=someotherplace,dc=org");
idf = new DefaultInitialDirContextFactory("ldap://acegisecurity.org/dc=acegisecurity,dc=org "
+ "ldap://monkeymachine.co.uk/dc=someotherplace,dc=org");
fail("Different root DNs should cause an exception");
} catch (IllegalArgumentException expected) {
}
} catch (IllegalArgumentException expected) {}
}
public void testSecureLdapUrlIsSupported() {
idf = new DefaultInitialDirContextFactory("ldaps://localhost/dc=acegisecurity,dc=org");
assertEquals("dc=acegisecurity,dc=org", idf.getRootDn());
}
// public void testNonLdapUrlIsRejected() throws Exception {
// DefaultInitialDirContextFactory idf = new DefaultInitialDirContextFactory();
//
// idf.setUrl("http://acegisecurity.org/dc=acegisecurity,dc=org");
// idf.setInitialContextFactory(CoreContextFactory.class.getName());
//
// try {
// idf.afterPropertiesSet();
// fail("Expected exception for non 'ldap://' URL");
// } catch(IllegalArgumentException expected) {
// }
// }
public void testServiceLocationUrlIsSupported() {
idf = new DefaultInitialDirContextFactory("ldap:///dc=acegisecurity,dc=org");
assertEquals("dc=acegisecurity,dc=org", idf.getRootDn());
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -15,43 +15,68 @@
package org.acegisecurity.ldap;
import javax.naming.directory.DirContext;
import javax.naming.NamingException;
import java.util.Set;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
/**
*
DOCUMENT ME!
*
* @author Luke Taylor
* @version $Id$
*/
public class LdapTemplateTests extends AbstractLdapServerTestCase {
//~ Instance fields ================================================================================================
private LdapTemplate template;
//~ Methods ========================================================================================================
protected void onSetUp() {
getInitialCtxFactory().setManagerDn(MANAGER_USER);
getInitialCtxFactory().setManagerPassword(MANAGER_PASSWORD);
template = new LdapTemplate(getInitialCtxFactory());
}
public void testCompareOfCorrectByteValueSucceeds() {
// Doesn't work with embedded server due to bugs in apacheds
// assertTrue(template.compare("uid=bob,ou=people,dc=acegisecurity,dc=org", "userPassword", LdapUtils.getUtf8Bytes("bobspassword")));
}
public void testCompareOfCorrectValueSucceeds() {
assertTrue(template.compare("uid=bob,ou=people,dc=acegisecurity,dc=org", "uid", "bob"));
}
public void testCompareOfWrongByteValueFails() {
// Doesn't work with embedded server due to bugs in apacheds
// assertFalse(template.compare("uid=bob,ou=people,dc=acegisecurity,dc=org", "userPassword", LdapUtils.getUtf8Bytes("wrongvalue")));
}
public void testCompareOfWrongValueFails() {
assertFalse(template.compare("uid=bob,ou=people,dc=acegisecurity,dc=org", "uid", "wrongvalue"));
}
public void testCompareOfCorrectByteValueSucceeds() {
// Doesn't work with embedded server due to bugs in apacheds
// assertTrue(template.compare("uid=bob,ou=people,dc=acegisecurity,dc=org", "userPassword", LdapUtils.getUtf8Bytes("bobspassword")));
public void testNameExistsForInValidNameFails() {
assertFalse(template.nameExists("ou=doesntexist,dc=acegisecurity,dc=org"));
}
public void testCompareOfWrongByteValueFails() {
public void testNameExistsForValidNameSucceeds() {
assertTrue(template.nameExists("ou=groups,dc=acegisecurity,dc=org"));
}
// Doesn't work with embedded server due to bugs in apacheds
// assertFalse(template.compare("uid=bob,ou=people,dc=acegisecurity,dc=org", "userPassword", LdapUtils.getUtf8Bytes("wrongvalue")));
public void testNamingExceptionIsTranslatedCorrectly() {
try {
template.execute(new LdapCallback() {
public Object doInDirContext(DirContext dirContext)
throws NamingException {
throw new NamingException();
}
});
fail("Expected LdapDataAccessException on NamingException");
} catch (LdapDataAccessException expected) {}
}
public void testSearchForSingleAttributeValues() {
@@ -63,26 +88,4 @@ public class LdapTemplateTests extends AbstractLdapServerTestCase {
assertTrue(values.contains("developer"));
assertTrue(values.contains("manager"));
}
public void testNameExistsForValidNameSucceeds() {
assertTrue(template.nameExists("ou=groups,dc=acegisecurity,dc=org"));
}
public void testNameExistsForInValidNameFails() {
assertFalse(template.nameExists("ou=doesntexist,dc=acegisecurity,dc=org"));
}
public void testNamingExceptionIsTranslatedCorrectly() {
try {
template.execute(new LdapCallback() {
public Object doInDirContext(DirContext dirContext) throws NamingException {
throw new NamingException();
}
});
fail("Expected LdapDataAccessException on NamingException");
}
catch(LdapDataAccessException expected) {
}
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -15,49 +15,47 @@
package org.acegisecurity.ldap;
import org.apache.directory.server.core.configuration.MutableStartupConfiguration;
import org.apache.directory.server.core.configuration.MutableDirectoryPartitionConfiguration;
import org.apache.directory.server.core.configuration.Configuration;
import org.apache.directory.server.core.configuration.MutableDirectoryPartitionConfiguration;
import org.apache.directory.server.core.configuration.MutableStartupConfiguration;
import org.apache.directory.server.core.jndi.CoreContextFactory;
import org.apache.directory.server.core.partition.DirectoryPartitionNexus;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.NameAlreadyBoundException;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.Attribute;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import java.util.Properties;
import java.util.Set;
import java.util.HashSet;
import java.io.File;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import javax.naming.Context;
import javax.naming.NameAlreadyBoundException;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
* An embedded LDAP test server, complete with test data for running the
* unit tests against.
* An embedded LDAP test server, complete with test data for running the unit tests against.
*
* @author Luke Taylor
* @version $Id$
*/
public class LdapTestServer {
//~ Instance fields ========================================================
//~ Instance fields ================================================================================================
private DirContext serverContext;
// Move the working dir to the temp directory
private File workingDir = new File(System.getProperty("java.io.tmpdir") + File.separator + "apacheds-work");
private MutableStartupConfiguration cfg;
// Move the working dir to the temp directory
private File workingDir = new File( System.getProperty("java.io.tmpdir")
+ File.separator + "apacheds-work" );
//~ Constructors ===================================================================================================
//~ Constructors ================================================================
/**
/**
* Starts up and configures ApacheDS.
*/
public LdapTestServer() {
@@ -66,125 +64,28 @@ public class LdapTestServer {
initTestData();
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
private void startLdapServer() {
cfg = new MutableStartupConfiguration();
((MutableStartupConfiguration)cfg).setWorkingDirectory(workingDir);
System.out.println("Working directory is " + workingDir.getAbsolutePath());
Properties env = new Properties();
env.setProperty( Context.PROVIDER_URL, "dc=acegisecurity,dc=org" );
env.setProperty( Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
env.setProperty( Context.SECURITY_AUTHENTICATION, "simple");
env.setProperty( Context.SECURITY_PRINCIPAL, DirectoryPartitionNexus.ADMIN_PRINCIPAL);
env.setProperty( Context.SECURITY_CREDENTIALS, DirectoryPartitionNexus.ADMIN_PASSWORD);
try {
initConfiguration();
env.putAll( cfg.toJndiEnvironment() );
serverContext = new InitialDirContext( env );
} catch (NamingException e) {
System.err.println("Failed to start Apache DS");
e.printStackTrace();
}
}
private void initTestData() {
createOu("people");
createOu("groups");
createUser("bob","Bob Hamilton", "bobspassword");
createUser("ben","Ben Alex", "{SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ=");
String[] developers = new String[]
{"uid=ben,ou=people,dc=acegisecurity,dc=org", "uid=bob,ou=people,dc=acegisecurity,dc=org"};
createGroup("developers","developer",developers);
createGroup("managers","manager", new String[] { developers[0]});
}
private void createManagerUser() {
Attributes user = new BasicAttributes( "cn", "manager" , true );
user.put( "userPassword", "acegisecurity" );
Attribute objectClass = new BasicAttribute("objectClass");
user.put( objectClass );
objectClass.add( "top" );
objectClass.add( "person" );
objectClass.add( "organizationalPerson" );
objectClass.add( "inetOrgPerson" );
user.put( "sn", "Manager" );
user.put( "cn", "manager" );
try {
serverContext.createSubcontext("cn=manager", user );
} catch(NameAlreadyBoundException ignore) {
// System.out.println("Manager user already exists.");
} catch (NamingException ne) {
System.err.println("Failed to create manager user.");
ne.printStackTrace();
}
}
public void createUser( String uid, String cn, String password ) {
Attributes user = new BasicAttributes("uid", uid);
user.put( "cn", cn);
user.put( "userPassword", LdapUtils.getUtf8Bytes(password) );
Attribute objectClass = new BasicAttribute( "objectClass" );
user.put( objectClass );
objectClass.add( "top" );
objectClass.add( "person" );
objectClass.add( "organizationalPerson" );
objectClass.add( "inetOrgPerson" );
user.put( "sn", uid );
try {
serverContext.createSubcontext( "uid="+uid+",ou=people", user );
} catch(NameAlreadyBoundException ignore) {
// System.out.println(" user " + uid + " already exists.");
} catch (NamingException ne) {
System.err.println("Failed to create user.");
ne.printStackTrace();
}
}
public void createOu(String name) {
Attributes ou = new BasicAttributes( "ou", name );
Attribute objectClass = new BasicAttribute( "objectClass" );
objectClass.add("top");
objectClass.add("organizationalUnit");
ou.put(objectClass);
try {
serverContext.createSubcontext( "ou="+name, ou);
} catch(NameAlreadyBoundException ignore) {
// System.out.println(" ou " + name + " already exists.");
} catch (NamingException ne) {
System.err.println("Failed to create ou.");
ne.printStackTrace();
}
}
public void createGroup( String cn, String ou, String[] memberDns ) {
public void createGroup(String cn, String ou, String[] memberDns) {
Attributes group = new BasicAttributes("cn", cn);
Attribute members = new BasicAttribute("member");
Attribute orgUnit = new BasicAttribute("ou", ou);
for(int i=0; i < memberDns.length; i++) {
for (int i = 0; i < memberDns.length; i++) {
members.add(memberDns[i]);
}
Attribute objectClass = new BasicAttribute( "objectClass" );
objectClass.add( "top" );
objectClass.add( "groupOfNames" );
Attribute objectClass = new BasicAttribute("objectClass");
objectClass.add("top");
objectClass.add("groupOfNames");
group.put(objectClass);
group.put(members);
group.put(orgUnit);
try {
serverContext.createSubcontext( "cn="+cn+",ou=groups", group );
} catch(NameAlreadyBoundException ignore) {
serverContext.createSubcontext("cn=" + cn + ",ou=groups", group);
} catch (NameAlreadyBoundException ignore) {
// System.out.println(" group " + cn + " already exists.");
} catch (NamingException ne) {
System.err.println("Failed to create group.");
@@ -192,12 +93,79 @@ public class LdapTestServer {
}
}
private void initConfiguration() throws NamingException {
private void createManagerUser() {
Attributes user = new BasicAttributes("cn", "manager", true);
user.put("userPassword", "acegisecurity");
Attribute objectClass = new BasicAttribute("objectClass");
user.put(objectClass);
objectClass.add("top");
objectClass.add("person");
objectClass.add("organizationalPerson");
objectClass.add("inetOrgPerson");
user.put("sn", "Manager");
user.put("cn", "manager");
try {
serverContext.createSubcontext("cn=manager", user);
} catch (NameAlreadyBoundException ignore) {
// System.out.println("Manager user already exists.");
} catch (NamingException ne) {
System.err.println("Failed to create manager user.");
ne.printStackTrace();
}
}
public void createOu(String name) {
Attributes ou = new BasicAttributes("ou", name);
Attribute objectClass = new BasicAttribute("objectClass");
objectClass.add("top");
objectClass.add("organizationalUnit");
ou.put(objectClass);
try {
serverContext.createSubcontext("ou=" + name, ou);
} catch (NameAlreadyBoundException ignore) {
// System.out.println(" ou " + name + " already exists.");
} catch (NamingException ne) {
System.err.println("Failed to create ou.");
ne.printStackTrace();
}
}
public void createUser(String uid, String cn, String password) {
Attributes user = new BasicAttributes("uid", uid);
user.put("cn", cn);
user.put("userPassword", LdapUtils.getUtf8Bytes(password));
Attribute objectClass = new BasicAttribute("objectClass");
user.put(objectClass);
objectClass.add("top");
objectClass.add("person");
objectClass.add("organizationalPerson");
objectClass.add("inetOrgPerson");
user.put("sn", uid);
try {
serverContext.createSubcontext("uid=" + uid + ",ou=people", user);
} catch (NameAlreadyBoundException ignore) {
// System.out.println(" user " + uid + " already exists.");
} catch (NamingException ne) {
System.err.println("Failed to create user.");
ne.printStackTrace();
}
}
public Configuration getConfiguration() {
return cfg;
}
private void initConfiguration() throws NamingException {
// Create the partition for the acegi tests
MutableDirectoryPartitionConfiguration acegiDit = new MutableDirectoryPartitionConfiguration();
acegiDit.setName("acegisecurity");
acegiDit.setSuffix("dc=acegisecurity,dc=org");
BasicAttributes attributes = new BasicAttributes();
BasicAttribute objectClass = new BasicAttribute("objectClass");
objectClass.add("top");
@@ -221,12 +189,44 @@ public class LdapTestServer {
cfg.setContextPartitionConfigurations(partitions);
}
public Configuration getConfiguration() {
return cfg;
private void initTestData() {
createOu("people");
createOu("groups");
createUser("bob", "Bob Hamilton", "bobspassword");
createUser("ben", "Ben Alex", "{SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ=");
String[] developers = new String[] {
"uid=ben,ou=people,dc=acegisecurity,dc=org", "uid=bob,ou=people,dc=acegisecurity,dc=org"
};
createGroup("developers", "developer", developers);
createGroup("managers", "manager", new String[] {developers[0]});
}
public static void main(String[] args) {
LdapTestServer server = new LdapTestServer();
}
private void startLdapServer() {
cfg = new MutableStartupConfiguration();
((MutableStartupConfiguration) cfg).setWorkingDirectory(workingDir);
System.out.println("Working directory is " + workingDir.getAbsolutePath());
Properties env = new Properties();
env.setProperty(Context.PROVIDER_URL, "dc=acegisecurity,dc=org");
env.setProperty(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
env.setProperty(Context.SECURITY_PRINCIPAL, DirectoryPartitionNexus.ADMIN_PRINCIPAL);
env.setProperty(Context.SECURITY_CREDENTIALS, DirectoryPartitionNexus.ADMIN_PASSWORD);
try {
initConfiguration();
env.putAll(cfg.toJndiEnvironment());
serverContext = new InitialDirContext(env);
} catch (NamingException e) {
System.err.println("Failed to start Apache DS");
e.printStackTrace();
}
}
}

View File

@@ -1,68 +1,78 @@
/* Copyright 2004, 2005 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.acegisecurity.ldap;
import org.jmock.MockObjectTestCase;
import org.jmock.Mock;
import javax.naming.directory.DirContext;
import javax.naming.Context;
import javax.naming.NamingException;
/**
* Tests {@link LdapUtils}
*
* @author Luke Taylor
* @version $Id$
*/
public class LdapUtilsTests extends MockObjectTestCase {
private final LdapDataAccessException tempCoverageBoost = new LdapDataAccessException("");
public void testRootDnsAreParsedFromUrlsCorrectly() {
assertEquals("", LdapUtils.parseRootDnFromUrl("ldap://monkeymachine"));
assertEquals("", LdapUtils.parseRootDnFromUrl("ldap://monkeymachine/"));
assertEquals("", LdapUtils.parseRootDnFromUrl("ldap://monkeymachine.co.uk/"));
assertEquals("dc=acegisecurity,dc=org", LdapUtils.parseRootDnFromUrl("ldaps://monkeymachine.co.uk/dc=acegisecurity,dc=org"));
assertEquals("dc=acegisecurity,dc=org", LdapUtils.parseRootDnFromUrl("ldap:///dc=acegisecurity,dc=org"));
assertEquals("dc=acegisecurity,dc=org", LdapUtils.parseRootDnFromUrl("ldap://monkeymachine/dc=acegisecurity,dc=org"));
assertEquals("dc=acegisecurity,dc=org/ou=blah", LdapUtils.parseRootDnFromUrl("ldap://monkeymachine.co.uk/dc=acegisecurity,dc=org/ou=blah"));
}
public void testGetRelativeNameReturnsFullDnWithEmptyBaseName() throws Exception {
Mock mockCtx = mock(DirContext.class);
mockCtx.expects(atLeastOnce()).method("getNameInNamespace").will(returnValue(""));
assertEquals("cn=jane,dc=acegisecurity,dc=org",
LdapUtils.getRelativeName("cn=jane,dc=acegisecurity,dc=org", (Context) mockCtx.proxy()));
}
public void testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName() throws Exception {
Mock mockCtx = mock(DirContext.class);
mockCtx.expects(atLeastOnce()).method("getNameInNamespace").will(returnValue("dc=acegisecurity,dc=org"));
assertEquals("", LdapUtils.getRelativeName("dc=acegisecurity,dc=org", (Context) mockCtx.proxy()));
}
public void testCloseContextSwallowsNamingException() {
Mock mockCtx = mock(DirContext.class);
mockCtx.expects(once()).method("close").will(throwException(new NamingException()));
LdapUtils.closeContext((Context) mockCtx.proxy());
}
}
/* 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.acegisecurity.ldap;
import org.jmock.Mock;
import org.jmock.MockObjectTestCase;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
/**
* Tests {@link LdapUtils}
*
* @author Luke Taylor
* @version $Id$
*/
public class LdapUtilsTests extends MockObjectTestCase {
//~ Instance fields ================================================================================================
private final LdapDataAccessException tempCoverageBoost = new LdapDataAccessException("");
//~ Methods ========================================================================================================
public void testCloseContextSwallowsNamingException() {
Mock mockCtx = mock(DirContext.class);
mockCtx.expects(once()).method("close").will(throwException(new NamingException()));
LdapUtils.closeContext((Context) mockCtx.proxy());
}
public void testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName()
throws Exception {
Mock mockCtx = mock(DirContext.class);
mockCtx.expects(atLeastOnce()).method("getNameInNamespace").will(returnValue("dc=acegisecurity,dc=org"));
assertEquals("", LdapUtils.getRelativeName("dc=acegisecurity,dc=org", (Context) mockCtx.proxy()));
}
public void testGetRelativeNameReturnsFullDnWithEmptyBaseName()
throws Exception {
Mock mockCtx = mock(DirContext.class);
mockCtx.expects(atLeastOnce()).method("getNameInNamespace").will(returnValue(""));
assertEquals("cn=jane,dc=acegisecurity,dc=org",
LdapUtils.getRelativeName("cn=jane,dc=acegisecurity,dc=org", (Context) mockCtx.proxy()));
}
public void testRootDnsAreParsedFromUrlsCorrectly() {
assertEquals("", LdapUtils.parseRootDnFromUrl("ldap://monkeymachine"));
assertEquals("", LdapUtils.parseRootDnFromUrl("ldap://monkeymachine/"));
assertEquals("", LdapUtils.parseRootDnFromUrl("ldap://monkeymachine.co.uk/"));
assertEquals("dc=acegisecurity,dc=org",
LdapUtils.parseRootDnFromUrl("ldaps://monkeymachine.co.uk/dc=acegisecurity,dc=org"));
assertEquals("dc=acegisecurity,dc=org", LdapUtils.parseRootDnFromUrl("ldap:///dc=acegisecurity,dc=org"));
assertEquals("dc=acegisecurity,dc=org",
LdapUtils.parseRootDnFromUrl("ldap://monkeymachine/dc=acegisecurity,dc=org"));
assertEquals("dc=acegisecurity,dc=org/ou=blah",
LdapUtils.parseRootDnFromUrl("ldap://monkeymachine.co.uk/dc=acegisecurity,dc=org/ou=blah"));
}
}

View File

@@ -1,29 +1,54 @@
package org.acegisecurity.ldap;
import javax.naming.directory.DirContext;
/**
* @author Luke Taylor
* @version $Id$
*/
public class MockInitialDirContextFactory implements InitialDirContextFactory {
DirContext ctx;
String baseDn;
public MockInitialDirContextFactory(DirContext ctx, String baseDn) {
this.baseDn = baseDn;
this.ctx = ctx;
}
public DirContext newInitialDirContext() {
return ctx;
}
public DirContext newInitialDirContext(String username, String password) {
return ctx;
}
public String getRootDn() {
return baseDn;
}
}
/* 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.acegisecurity.ldap;
import javax.naming.directory.DirContext;
/**
*
DOCUMENT ME!
*
* @author Luke Taylor
* @version $Id$
*/
public class MockInitialDirContextFactory implements InitialDirContextFactory {
//~ Instance fields ================================================================================================
DirContext ctx;
String baseDn;
//~ Constructors ===================================================================================================
public MockInitialDirContextFactory(DirContext ctx, String baseDn) {
this.baseDn = baseDn;
this.ctx = ctx;
}
//~ Methods ========================================================================================================
public String getRootDn() {
return baseDn;
}
public DirContext newInitialDirContext() {
return ctx;
}
public DirContext newInitialDirContext(String username, String password) {
return ctx;
}
}

View File

@@ -1,25 +1,41 @@
/* 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.acegisecurity.ldap.search;
import org.acegisecurity.ldap.AbstractLdapServerTestCase;
import org.acegisecurity.ldap.DefaultInitialDirContextFactory;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.acegisecurity.userdetails.ldap.LdapUserDetails;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
/**
* Tests for FilterBasedLdapUserSearch.
*
*
* @author Luke Taylor
* @version $Id$
*/
public class FilterBasedLdapUserSearchTests extends AbstractLdapServerTestCase {
//~ Instance fields ================================================================================================
private DefaultInitialDirContextFactory dirCtxFactory;
public void onSetUp() {
dirCtxFactory = getInitialCtxFactory();
dirCtxFactory.setManagerDn(MANAGER_USER);
dirCtxFactory.setManagerPassword(MANAGER_PASSWORD);
}
//~ Constructors ===================================================================================================
public FilterBasedLdapUserSearchTests(String string) {
super(string);
@@ -29,64 +45,66 @@ public class FilterBasedLdapUserSearchTests extends AbstractLdapServerTestCase {
super();
}
//~ Methods ========================================================================================================
public void onSetUp() {
dirCtxFactory = getInitialCtxFactory();
dirCtxFactory.setManagerDn(MANAGER_USER);
dirCtxFactory.setManagerPassword(MANAGER_PASSWORD);
}
public void testBasicSearch() {
FilterBasedLdapUserSearch locator =
new FilterBasedLdapUserSearch("ou=people", "(uid={0})", dirCtxFactory);
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people", "(uid={0})", dirCtxFactory);
locator.setSearchSubtree(false);
locator.setSearchTimeLimit(0);
locator.setDerefLinkFlag(false);
LdapUserDetails bob = locator.searchForUser("bob");
assertEquals("bob", bob.getUsername());
// name is wrong with embedded apacheDS
// assertEquals("uid=bob,ou=people,dc=acegisecurity,dc=org", bob.getDn());
}
public void testSubTreeSearchSucceeds() {
// Don't set the searchBase, so search from the root.
FilterBasedLdapUserSearch locator =
new FilterBasedLdapUserSearch("", "(cn={0})", dirCtxFactory);
locator.setSearchSubtree(true);
// Try some funny business with filters.
public void testExtraFilterPartToExcludeBob() throws Exception {
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people",
"(&(cn=*)(!(|(uid={0})(uid=marissa))))", dirCtxFactory);
LdapUserDetails ben = locator.searchForUser("Ben Alex");
assertEquals("Ben Alex", ben.getUsername());
// assertEquals("uid=ben,ou=people,dc=acegisecurity,dc=org", ben.getDn());
}
// Search for bob, get back ben...
LdapUserDetails ben = locator.searchForUser("bob");
String cn = (String) ben.getAttributes().get("cn").get();
assertEquals("Ben Alex", cn);
public void testSearchForInvalidUserFails() {
FilterBasedLdapUserSearch locator =
new FilterBasedLdapUserSearch("ou=people", "(uid={0})", dirCtxFactory);
try {
locator.searchForUser("Joe");
fail("Expected UsernameNotFoundException for non-existent user.");
} catch (UsernameNotFoundException expected) {
}
// assertEquals("uid=ben,ou=people,"+ROOT_DN, ben.getDn());
}
public void testFailsOnMultipleMatches() {
FilterBasedLdapUserSearch locator =
new FilterBasedLdapUserSearch("ou=people", "(cn=*)", dirCtxFactory);
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people", "(cn=*)", dirCtxFactory);
try {
locator.searchForUser("Ignored");
fail("Expected exception for multiple search matches.");
} catch (IncorrectResultSizeDataAccessException expected) {
}
} catch (IncorrectResultSizeDataAccessException expected) {}
}
// Try some funny business with filters.
public void testSearchForInvalidUserFails() {
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people", "(uid={0})", dirCtxFactory);
public void testExtraFilterPartToExcludeBob() throws Exception {
FilterBasedLdapUserSearch locator =
new FilterBasedLdapUserSearch("ou=people",
"(&(cn=*)(!(|(uid={0})(uid=marissa))))",
dirCtxFactory);
try {
locator.searchForUser("Joe");
fail("Expected UsernameNotFoundException for non-existent user.");
} catch (UsernameNotFoundException expected) {}
}
// Search for bob, get back ben...
LdapUserDetails ben = locator.searchForUser("bob");
String cn = (String)ben.getAttributes().get("cn").get();
assertEquals("Ben Alex", cn);
// assertEquals("uid=ben,ou=people,"+ROOT_DN, ben.getDn());
public void testSubTreeSearchSucceeds() {
// Don't set the searchBase, so search from the root.
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("", "(cn={0})", dirCtxFactory);
locator.setSearchSubtree(true);
LdapUserDetails ben = locator.searchForUser("Ben Alex");
assertEquals("Ben Alex", ben.getUsername());
// assertEquals("uid=ben,ou=people,dc=acegisecurity,dc=org", ben.getDn());
}
}

View File

@@ -28,11 +28,11 @@ import org.acegisecurity.GrantedAuthorityImpl;
* @version $Id$
*/
public class AbstractAuthenticationTokenTests extends TestCase {
//~ Instance fields ========================================================
//~ Instance fields ================================================================================================
private GrantedAuthority[] authorities = null;
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AbstractAuthenticationTokenTests() {
super();
@@ -42,7 +42,7 @@ public class AbstractAuthenticationTokenTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AbstractAuthenticationTokenTests.class);
@@ -51,90 +51,11 @@ public class AbstractAuthenticationTokenTests extends TestCase {
public final void setUp() throws Exception {
super.setUp();
authorities = new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"),
new GrantedAuthorityImpl("ROLE_TWO")};
}
public void testGetters() throws Exception {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test",
"Password", authorities);
assertEquals("Test", token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertEquals("Test", token.getName());
}
public void testHashCode() throws Exception {
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test",
"Password", authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test",
"Password", authorities);
MockAuthenticationImpl token3 = new MockAuthenticationImpl(null, null,
new GrantedAuthority[] {});
assertEquals(token1.hashCode(), token2.hashCode());
assertTrue(token1.hashCode() != token3.hashCode());
token2.setAuthenticated(true);
assertTrue(token1.hashCode() != token2.hashCode());
}
public void testObjectsEquals() throws Exception {
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test",
"Password", authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test",
"Password", authorities);
assertEquals(token1, token2);
MockAuthenticationImpl token3 = new MockAuthenticationImpl("Test",
"Password_Changed", authorities);
assertTrue(!token1.equals(token3));
MockAuthenticationImpl token4 = new MockAuthenticationImpl("Test_Changed",
"Password", authorities);
assertTrue(!token1.equals(token4));
MockAuthenticationImpl token5 = new MockAuthenticationImpl("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO_CHANGED")});
assertTrue(!token1.equals(token5));
MockAuthenticationImpl token6 = new MockAuthenticationImpl("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE")});
assertTrue(!token1.equals(token6));
MockAuthenticationImpl token7 = new MockAuthenticationImpl("Test",
"Password", null);
assertTrue(!token1.equals(token7));
assertTrue(!token7.equals(token1));
assertTrue(!token1.equals(new Integer(100)));
}
public void testSetAuthenticated() throws Exception {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test",
"Password", authorities);
assertTrue(!token.isAuthenticated());
token.setAuthenticated(true);
assertTrue(token.isAuthenticated());
}
public void testToStringWithAuthorities() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test",
"Password", authorities);
assertTrue(token.toString().lastIndexOf("ROLE_TWO") != -1);
}
public void testToStringWithNullAuthorities() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test",
"Password", null);
assertTrue(token.toString().lastIndexOf("Not granted any authorities") != -1);
authorities = new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")};
}
public void testAuthoritiesAreImmutable() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test",
"Password", authorities);
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
GrantedAuthority[] gotAuthorities = token.getAuthorities();
assertNotSame(authorities, gotAuthorities);
@@ -146,17 +67,80 @@ public class AbstractAuthenticationTokenTests extends TestCase {
assertEquals(gotAuthorities[0], authorities[0]);
assertEquals(gotAuthorities[1], authorities[1]);
assertFalse(gotAuthorities[0].equals("ROLE_SUPER_USER"));
assertFalse(gotAuthorities[1].equals("ROLE_SUPER_USER"));
assertFalse(gotAuthorities[1].equals("ROLE_SUPER_USER"));
}
//~ Inner Classes ==========================================================
public void testGetters() throws Exception {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
assertEquals("Test", token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertEquals("Test", token.getName());
}
public void testHashCode() throws Exception {
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token3 = new MockAuthenticationImpl(null, null, new GrantedAuthority[] {});
assertEquals(token1.hashCode(), token2.hashCode());
assertTrue(token1.hashCode() != token3.hashCode());
token2.setAuthenticated(true);
assertTrue(token1.hashCode() != token2.hashCode());
}
public void testObjectsEquals() throws Exception {
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password", authorities);
assertEquals(token1, token2);
MockAuthenticationImpl token3 = new MockAuthenticationImpl("Test", "Password_Changed", authorities);
assertTrue(!token1.equals(token3));
MockAuthenticationImpl token4 = new MockAuthenticationImpl("Test_Changed", "Password", authorities);
assertTrue(!token1.equals(token4));
MockAuthenticationImpl token5 = new MockAuthenticationImpl("Test", "Password",
new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO_CHANGED")
});
assertTrue(!token1.equals(token5));
MockAuthenticationImpl token6 = new MockAuthenticationImpl("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE")});
assertTrue(!token1.equals(token6));
MockAuthenticationImpl token7 = new MockAuthenticationImpl("Test", "Password", null);
assertTrue(!token1.equals(token7));
assertTrue(!token7.equals(token1));
assertTrue(!token1.equals(new Integer(100)));
}
public void testSetAuthenticated() throws Exception {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
assertTrue(!token.isAuthenticated());
token.setAuthenticated(true);
assertTrue(token.isAuthenticated());
}
public void testToStringWithAuthorities() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
assertTrue(token.toString().lastIndexOf("ROLE_TWO") != -1);
}
public void testToStringWithNullAuthorities() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", null);
assertTrue(token.toString().lastIndexOf("Not granted any authorities") != -1);
}
//~ Inner Classes ==================================================================================================
private class MockAuthenticationImpl extends AbstractAuthenticationToken {
private Object credentials;
private Object principal;
public MockAuthenticationImpl(Object principal, Object credentials,
GrantedAuthority[] authorities) {
public MockAuthenticationImpl(Object principal, Object credentials, GrantedAuthority[] authorities) {
super(authorities);
this.principal = principal;
this.credentials = credentials;

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -15,9 +15,6 @@
package org.acegisecurity.providers;
import java.util.List;
import java.util.Vector;
import junit.framework.TestCase;
import org.acegisecurity.Authentication;
@@ -25,11 +22,16 @@ import org.acegisecurity.AuthenticationException;
import org.acegisecurity.AuthenticationServiceException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.concurrent.ConcurrentSessionControllerImpl;
import org.acegisecurity.concurrent.NullConcurrentSessionController;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import java.util.List;
import java.util.Vector;
/**
* Tests {@link ProviderManager}.
@@ -38,7 +40,7 @@ import org.springframework.context.ApplicationEventPublisher;
* @version $Id$
*/
public class ProviderManagerTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public ProviderManagerTests() {
super();
@@ -48,21 +50,45 @@ public class ProviderManagerTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(ProviderManagerTests.class);
}
private ProviderManager makeProviderManager() throws Exception {
MockProvider provider1 = new MockProvider();
List providers = new Vector();
providers.add(provider1);
ProviderManager mgr = new ProviderManager();
mgr.setProviders(providers);
mgr.afterPropertiesSet();
return mgr;
}
private ProviderManager makeProviderManagerWithMockProviderWhichReturnsNullInList() {
MockProviderWhichReturnsNull provider1 = new MockProviderWhichReturnsNull();
MockProvider provider2 = new MockProvider();
List providers = new Vector();
providers.add(provider1);
providers.add(provider2);
ProviderManager mgr = new ProviderManager();
mgr.setProviders(providers);
return mgr;
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAuthenticationFails() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
ProviderManager mgr = makeProviderManager();
mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true));
@@ -76,13 +102,12 @@ public class ProviderManagerTests extends TestCase {
}
public void testAuthenticationSuccess() throws Exception {
TestingAuthenticationToken token = new TestingAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
ProviderManager mgr = makeProviderManager();
mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true));
Authentication result = mgr.authenticate(token);
if (!(result instanceof TestingAuthenticationToken)) {
@@ -97,13 +122,12 @@ public class ProviderManagerTests extends TestCase {
}
public void testAuthenticationSuccessWhenFirstProviderReturnsNullButSecondAuthenticates() {
TestingAuthenticationToken token = new TestingAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
ProviderManager mgr = makeProviderManagerWithMockProviderWhichReturnsNullInList();
mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true));
Authentication result = mgr.authenticate(token);
if (!(result instanceof TestingAuthenticationToken)) {
@@ -175,47 +199,34 @@ public class ProviderManagerTests extends TestCase {
assertEquals(1, mgr.getProviders().size());
}
private ProviderManager makeProviderManager() throws Exception {
MockProvider provider1 = new MockProvider();
List providers = new Vector();
providers.add(provider1);
//~ Inner Classes ==================================================================================================
ProviderManager mgr = new ProviderManager();
mgr.setProviders(providers);
mgr.afterPropertiesSet();
return mgr;
private class MockApplicationEventPublisher implements ApplicationEventPublisher {
private boolean expectedEvent;
public MockApplicationEventPublisher(boolean expectedEvent) {
this.expectedEvent = expectedEvent;
}
public void publishEvent(ApplicationEvent event) {
if (expectedEvent == false) {
throw new IllegalStateException("The ApplicationEventPublisher did not expect to receive this event");
}
}
}
private ProviderManager makeProviderManagerWithMockProviderWhichReturnsNullInList() {
MockProviderWhichReturnsNull provider1 = new MockProviderWhichReturnsNull();
MockProvider provider2 = new MockProvider();
List providers = new Vector();
providers.add(provider1);
providers.add(provider2);
ProviderManager mgr = new ProviderManager();
mgr.setProviders(providers);
return mgr;
}
//~ Inner Classes ==========================================================
private class MockProvider implements AuthenticationProvider {
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
if (supports(authentication.getClass())) {
return authentication;
} else {
throw new AuthenticationServiceException(
"Don't support this class");
throw new AuthenticationServiceException("Don't support this class");
}
}
public boolean supports(Class authentication) {
if (TestingAuthenticationToken.class.isAssignableFrom(
authentication)) {
if (TestingAuthenticationToken.class.isAssignableFrom(authentication)) {
return true;
} else {
return false;
@@ -229,32 +240,16 @@ public class ProviderManagerTests extends TestCase {
if (supports(authentication.getClass())) {
return null;
} else {
throw new AuthenticationServiceException(
"Don't support this class");
throw new AuthenticationServiceException("Don't support this class");
}
}
public boolean supports(Class authentication) {
if (TestingAuthenticationToken.class.isAssignableFrom(
authentication)) {
if (TestingAuthenticationToken.class.isAssignableFrom(authentication)) {
return true;
} else {
return false;
}
}
}
private class MockApplicationEventPublisher implements ApplicationEventPublisher {
private boolean expectedEvent;
public MockApplicationEventPublisher(boolean expectedEvent) {
this.expectedEvent = expectedEvent;
}
public void publishEvent(ApplicationEvent event) {
if (expectedEvent == false) {
throw new IllegalStateException("The ApplicationEventPublisher did not expect to receive this event");
}
}
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* 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.
@@ -29,7 +29,7 @@ import org.acegisecurity.GrantedAuthorityImpl;
* @version $Id$
*/
public class TestingAuthenticationProviderTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public TestingAuthenticationProviderTests() {
super();
@@ -39,22 +39,20 @@ public class TestingAuthenticationProviderTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(TestingAuthenticationProviderTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAuthenticates() {
TestingAuthenticationProvider provider = new TestingAuthenticationProvider();
TestingAuthenticationToken token = new TestingAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
Authentication result = provider.authenticate(token);
if (!(result instanceof TestingAuthenticationToken)) {

View File

@@ -28,7 +28,7 @@ import org.acegisecurity.GrantedAuthorityImpl;
* @version $Id$
*/
public class TestingAuthenticationTokenTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public TestingAuthenticationTokenTests() {
super();
@@ -38,7 +38,7 @@ public class TestingAuthenticationTokenTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(TestingAuthenticationTokenTests.class);
@@ -49,18 +49,15 @@ public class TestingAuthenticationTokenTests extends TestCase {
}
public void testAuthenticated() {
TestingAuthenticationToken token = new TestingAuthenticationToken("Test",
"Password", null);
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password", null);
assertTrue(!token.isAuthenticated());
token.setAuthenticated(true);
assertTrue(token.isAuthenticated());
}
public void testGetters() {
TestingAuthenticationToken token = new TestingAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertEquals("Test", token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertEquals("ROLE_ONE", token.getAuthorities()[0].getAuthority());

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -28,7 +28,7 @@ import org.acegisecurity.GrantedAuthorityImpl;
* @version $Id$
*/
public class UsernamePasswordAuthenticationTokenTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public UsernamePasswordAuthenticationTokenTests() {
super();
@@ -38,19 +38,18 @@ public class UsernamePasswordAuthenticationTokenTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(UsernamePasswordAuthenticationTokenTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAuthenticated() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password", null);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", null);
// check default given we passed some GrantedAuthorty[]s (well, we passed null)
assertTrue(token.isAuthenticated());
@@ -78,10 +77,8 @@ public class UsernamePasswordAuthenticationTokenTests extends TestCase {
}
public void testGetters() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertEquals("Test", token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertEquals("ROLE_ONE", token.getAuthorities()[0].getAuthority());
@@ -92,7 +89,7 @@ public class UsernamePasswordAuthenticationTokenTests extends TestCase {
Class clazz = UsernamePasswordAuthenticationToken.class;
try {
clazz.getDeclaredConstructor((Class[])null);
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
} catch (NoSuchMethodException expected) {
assertTrue(true);

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -21,6 +21,7 @@ import org.acegisecurity.Authentication;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.providers.TestingAuthenticationToken;
@@ -31,7 +32,7 @@ import org.acegisecurity.providers.TestingAuthenticationToken;
* @version $Id$
*/
public class AnonymousAuthenticationProviderTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AnonymousAuthenticationProviderTests() {
super();
@@ -41,24 +42,22 @@ public class AnonymousAuthenticationProviderTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AnonymousAuthenticationProviderTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testDetectsAnInvalidKey() throws Exception {
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider();
aap.setKey("qwerty");
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("WRONG_KEY",
"Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("WRONG_KEY", "Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
try {
Authentication result = aap.authenticate(token);
@@ -91,8 +90,7 @@ public class AnonymousAuthenticationProviderTests extends TestCase {
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider();
aap.setKey("qwerty");
TestingAuthenticationToken token = new TestingAuthenticationToken("user",
"password",
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")});
assertFalse(aap.supports(TestingAuthenticationToken.class));
@@ -104,10 +102,8 @@ public class AnonymousAuthenticationProviderTests extends TestCase {
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider();
aap.setKey("qwerty");
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("qwerty",
"Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("qwerty", "Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
Authentication result = aap.authenticate(token);

View File

@@ -33,7 +33,7 @@ import java.util.Vector;
* @version $Id$
*/
public class AnonymousAuthenticationTokenTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AnonymousAuthenticationTokenTests() {
super();
@@ -43,7 +43,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AnonymousAuthenticationTokenTests.class);
@@ -56,8 +56,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
public void testConstructorRejectsNulls() {
try {
new AnonymousAuthenticationToken(null, "Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
@@ -65,8 +64,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
try {
new AnonymousAuthenticationToken("key", null,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
@@ -80,16 +78,14 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
}
try {
new AnonymousAuthenticationToken("key", "Test",
new GrantedAuthority[] {null});
new AnonymousAuthenticationToken("key", "Test", new GrantedAuthority[] {null});
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new AnonymousAuthenticationToken("key", "Test",
new GrantedAuthority[] {});
new AnonymousAuthenticationToken("key", "Test", new GrantedAuthority[] {});
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
@@ -100,24 +96,18 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
List proxyList1 = new Vector();
proxyList1.add("https://localhost/newPortal/j_acegi_cas_security_check");
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key",
"Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key",
"Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key", "Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertEquals(token1, token2);
}
public void testGetters() {
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key",
"Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", "Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertEquals("key".hashCode(), token.getKeyHash());
assertEquals("Test", token.getPrincipal());
@@ -139,52 +129,38 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
}
public void testNotEqualsDueToAbstractParentEqualsCheck() {
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key",
"Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key",
"DIFFERENT_PRINCIPAL",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key", "DIFFERENT_PRINCIPAL",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertFalse(token1.equals(token2));
}
public void testNotEqualsDueToDifferentAuthenticationClass() {
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key",
"Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertFalse(token1.equals(token2));
}
public void testNotEqualsDueToKey() {
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key",
"Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("DIFFERENT_KEY",
"Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("DIFFERENT_KEY", "Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertFalse(token1.equals(token2));
}
public void testSetAuthenticatedIgnored() {
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key",
"Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", "Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertTrue(token.isAuthenticated());
token.setAuthenticated(false);
assertTrue(!token.isAuthenticated());

View File

@@ -48,7 +48,7 @@ import javax.servlet.ServletResponse;
* @version $Id$
*/
public class AnonymousProcessingFilterTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public AnonymousProcessingFilterTests() {
super();
@@ -58,11 +58,11 @@ public class AnonymousProcessingFilterTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
//~ Methods ========================================================================================================
private void executeFilterInContainerSimulator(FilterConfig filterConfig,
Filter filter, ServletRequest request, ServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
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();
@@ -130,8 +130,7 @@ public class AnonymousProcessingFilterTests extends TestCase {
public void testOperationWhenAuthenticationExistsInContextHolder()
throws Exception {
// Put an Authentication object into the SecurityContextHolder
Authentication originalAuth = new TestingAuthenticationToken("user",
"password",
Authentication originalAuth = new TestingAuthenticationToken("user", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")});
SecurityContextHolder.getContext().setAuthentication(originalAuth);
@@ -148,12 +147,11 @@ public class AnonymousProcessingFilterTests extends TestCase {
// Test
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("x");
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, new MockHttpServletResponse(), new MockFilterChain(true));
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, new MockHttpServletResponse(),
new MockFilterChain(true));
// Ensure filter didn't change our original object
assertEquals(originalAuth,
SecurityContextHolder.getContext().getAuthentication());
assertEquals(originalAuth, SecurityContextHolder.getContext().getAuthentication());
}
public void testOperationWhenNoAuthenticationInSecurityContextHolder()
@@ -170,24 +168,22 @@ public class AnonymousProcessingFilterTests extends TestCase {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("x");
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, new MockHttpServletResponse(), new MockFilterChain(true));
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, new MockHttpServletResponse(),
new MockFilterChain(true));
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
assertEquals("anonymousUsername", auth.getPrincipal());
assertEquals(new GrantedAuthorityImpl("ROLE_ANONYMOUS"),
auth.getAuthorities()[0]);
assertEquals(new GrantedAuthorityImpl("ROLE_ANONYMOUS"), auth.getAuthorities()[0]);
SecurityContextHolder.getContext().setAuthentication(null); // so anonymous fires again
// Now test operation if we have removeAfterRequest = true
filter.setRemoveAfterRequest(true); // set to default value
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, new MockHttpServletResponse(), new MockFilterChain(true));
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, new MockHttpServletResponse(),
new MockFilterChain(true));
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockFilterChain implements FilterChain {
private boolean expectToProceed;

View File

@@ -1,4 +1,4 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
/* 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.
@@ -15,11 +15,6 @@
package org.acegisecurity.providers.cas;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import junit.framework.TestCase;
import org.acegisecurity.Authentication;
@@ -27,13 +22,21 @@ import org.acegisecurity.AuthenticationException;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.providers.TestingAuthenticationToken;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.cas.ticketvalidator.AbstractTicketValidator;
import org.acegisecurity.ui.cas.CasProcessingFilter;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
/**
* Tests {@link CasAuthenticationProvider}.
@@ -42,7 +45,7 @@ import org.acegisecurity.userdetails.UserDetails;
* @version $Id$
*/
public class CasAuthenticationProviderTests extends TestCase {
//~ Constructors ===========================================================
//~ Constructors ===================================================================================================
public CasAuthenticationProviderTests() {
super();
@@ -52,16 +55,26 @@ public class CasAuthenticationProviderTests extends TestCase {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(CasAuthenticationProviderTests.class);
}
private UserDetails makeUserDetails() {
return new User("user", "password", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
}
private UserDetails makeUserDetailsFromAuthoritiesPopulator() {
return new User("user", "password", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B")});
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAuthenticateStateful() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setCasAuthoritiesPopulator(new MockAuthoritiesPopulator());
@@ -89,13 +102,10 @@ public class CasAuthenticationProviderTests extends TestCase {
assertEquals(makeUserDetailsFromAuthoritiesPopulator(), casResult.getPrincipal());
assertEquals("PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt",
casResult.getProxyGrantingTicketIou());
assertEquals("https://localhost/portal/j_acegi_cas_security_check",
casResult.getProxyList().get(0));
assertEquals("https://localhost/portal/j_acegi_cas_security_check", casResult.getProxyList().get(0));
assertEquals("ST-123", casResult.getCredentials());
assertEquals(new GrantedAuthorityImpl("ROLE_A"),
casResult.getAuthorities()[0]);
assertEquals(new GrantedAuthorityImpl("ROLE_B"),
casResult.getAuthorities()[1]);
assertEquals(new GrantedAuthorityImpl("ROLE_A"), casResult.getAuthorities()[0]);
assertEquals(new GrantedAuthorityImpl("ROLE_B"), casResult.getAuthorities()[1]);
assertEquals(cap.getKey().hashCode(), casResult.getKeyHash());
// Now confirm the CasAuthenticationToken is automatically re-accepted.
@@ -160,8 +170,7 @@ public class CasAuthenticationProviderTests extends TestCase {
Authentication result = cap.authenticate(token);
fail("Should have thrown BadCredentialsException");
} catch (BadCredentialsException expected) {
assertEquals("Failed to provide a CAS service ticket to validate",
expected.getMessage());
assertEquals("Failed to provide a CAS service ticket to validate", expected.getMessage());
}
}
@@ -176,17 +185,14 @@ public class CasAuthenticationProviderTests extends TestCase {
cap.setTicketValidator(new MockTicketValidator(true));
cap.afterPropertiesSet();
CasAuthenticationToken token = new CasAuthenticationToken("WRONG_KEY",
makeUserDetails(), "credentials",
new GrantedAuthority[] {new GrantedAuthorityImpl("XX")},
makeUserDetails(), new Vector(), "IOU-xxx");
CasAuthenticationToken token = new CasAuthenticationToken("WRONG_KEY", makeUserDetails(), "credentials",
new GrantedAuthority[] {new GrantedAuthorityImpl("XX")}, makeUserDetails(), new Vector(), "IOU-xxx");
try {
Authentication result = cap.authenticate(token);
fail("Should have thrown BadCredentialsException");
} catch (BadCredentialsException expected) {
assertEquals("The presented CasAuthenticationToken does not contain the expected key",
expected.getMessage());
assertEquals("The presented CasAuthenticationToken does not contain the expected key", expected.getMessage());
}
}
@@ -202,8 +208,7 @@ public class CasAuthenticationProviderTests extends TestCase {
cap.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("A casAuthoritiesPopulator must be set",
expected.getMessage());
assertEquals("A casAuthoritiesPopulator must be set", expected.getMessage());
}
}
@@ -250,8 +255,7 @@ public class CasAuthenticationProviderTests extends TestCase {
cap.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("A statelessTicketCache must be set",
expected.getMessage());
assertEquals("A statelessTicketCache must be set", expected.getMessage());
}
}
@@ -295,8 +299,7 @@ public class CasAuthenticationProviderTests extends TestCase {
cap.setTicketValidator(new MockTicketValidator(true));
cap.afterPropertiesSet();
TestingAuthenticationToken token = new TestingAuthenticationToken("user",
"password",
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")});
assertFalse(cap.supports(TestingAuthenticationToken.class));
@@ -315,8 +318,7 @@ public class CasAuthenticationProviderTests extends TestCase {
cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("some_normal_user",
"password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")});
"password", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")});
assertEquals(null, cap.authenticate(token));
}
@@ -326,19 +328,7 @@ public class CasAuthenticationProviderTests extends TestCase {
assertTrue(cap.supports(CasAuthenticationToken.class));
}
private UserDetails makeUserDetails() {
return new User("user", "password", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
}
private UserDetails makeUserDetailsFromAuthoritiesPopulator() {
return new User("user", "password", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl(
"ROLE_B")});
}
//~ Inner Classes ==========================================================
//~ Inner Classes ==================================================================================================
private class MockAuthoritiesPopulator implements CasAuthoritiesPopulator {
public UserDetails getUserDetails(String casUserId)
@@ -380,13 +370,11 @@ public class CasAuthenticationProviderTests extends TestCase {
}
public void removeTicketFromCache(CasAuthenticationToken token) {
throw new UnsupportedOperationException(
"mock method not implemented");
throw new UnsupportedOperationException("mock method not implemented");
}
public void removeTicketFromCache(String serviceTicket) {
throw new UnsupportedOperationException(
"mock method not implemented");
throw new UnsupportedOperationException("mock method not implemented");
}
}
@@ -407,8 +395,7 @@ public class CasAuthenticationProviderTests extends TestCase {
List list = new Vector();
list.add("https://localhost/portal/j_acegi_cas_security_check");
return new TicketResponse("marissa", list,
"PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
return new TicketResponse("marissa", list, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
}
throw new BadCredentialsException("As requested from mock");

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