Refactor DaoAuthenticationProvider cache model.

This commit is contained in:
Ben Alex
2004-05-31 04:41:22 +00:00
parent d9f77a7ed1
commit 1b24ff5ea8
19 changed files with 517 additions and 600 deletions

View File

@@ -36,7 +36,6 @@
<!-- Authentication provider that queries our data access object -->
<bean id="daoAuthenticationProvider" class="net.sf.acegisecurity.providers.dao.DaoAuthenticationProvider">
<property name="authenticationDao"><ref bean="inMemoryDaoImpl"/></property>
<property name="key"><value>my_password</value></property>
</bean>
<!-- The authentication manager that iterates through our only authentication provider -->

View File

@@ -25,13 +25,16 @@ import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.providers.TestingAuthenticationToken;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import net.sf.acegisecurity.providers.dao.cache.EhCacheBasedUserCache;
import net.sf.acegisecurity.providers.dao.cache.NullUserCache;
import net.sf.acegisecurity.providers.dao.salt.SystemWideSaltSource;
import net.sf.acegisecurity.providers.encoding.ShaPasswordEncoder;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataRetrievalFailureException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
@@ -56,8 +59,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
"KOala");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setKey("x");
provider.setAuthenticationDao(new MockAuthenticationDaoUserMarissa());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
@@ -72,8 +75,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
"opal");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setKey("x");
provider.setAuthenticationDao(new MockAuthenticationDaoUserPeter());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
@@ -88,8 +91,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
"koala");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setKey("x");
provider.setAuthenticationDao(new MockAuthenticationDaoSimulateBackendError());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
@@ -104,8 +107,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
"INVALID_PASSWORD");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setKey("x");
provider.setAuthenticationDao(new MockAuthenticationDaoUserMarissa());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
@@ -120,8 +123,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
"koala");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setKey("x");
provider.setAuthenticationDao(new MockAuthenticationDaoUserMarissa());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
@@ -136,8 +139,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
"koala");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setKey("x");
provider.setAuthenticationDao(new MockAuthenticationDaoUserMarissa());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
@@ -152,55 +155,21 @@ public class DaoAuthenticationProviderTests extends TestCase {
"koala");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setKey("x");
provider.setAuthenticationDao(new MockAuthenticationDaoUserMarissa());
provider.setUserCache(new MockUserCache());
Authentication result = provider.authenticate(token);
if (!(result instanceof DaoAuthenticationToken)) {
fail("Should have returned instance of DaoAuthenticationToken");
if (!(result instanceof UsernamePasswordAuthenticationToken)) {
fail(
"Should have returned instance of UsernamePasswordAuthenticationToken");
}
DaoAuthenticationToken castResult = (DaoAuthenticationToken) result;
UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;
assertEquals("marissa", castResult.getPrincipal());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
assertEquals(provider.getKey().hashCode(), castResult.getKeyHash());
}
public void testAuthenticatesThenAcceptsCreatedTokenAutomatically() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("marissa",
"koala");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setKey("x");
provider.setAuthenticationDao(new MockAuthenticationDaoUserMarissa());
Authentication result = provider.authenticate(token);
if (!(result instanceof DaoAuthenticationToken)) {
fail("Should have returned instance of DaoAuthenticationToken");
}
DaoAuthenticationToken castResult = (DaoAuthenticationToken) result;
assertEquals("marissa", castResult.getPrincipal());
assertEquals(provider.getKey().hashCode(), castResult.getKeyHash());
assertTrue(castResult.getExpires().after(new Date()));
// Now try to re-authenticate
// Set provider to null, so we get a NullPointerException if it tries to re-authenticate
provider.setAuthenticationDao(null);
Authentication secondResult = provider.authenticate(result);
if (!(secondResult instanceof DaoAuthenticationToken)) {
fail("Should have returned instance of DaoAuthenticationToken");
}
// Should still have the same expiry time as original
assertEquals(castResult.getExpires(),
((DaoAuthenticationToken) secondResult).getExpires());
}
public void testAuthenticatesWhenASaltIsUsed() {
@@ -211,77 +180,22 @@ public class DaoAuthenticationProviderTests extends TestCase {
salt.setSystemWideSalt("SYSTEM_SALT_VALUE");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setKey("x");
provider.setAuthenticationDao(new MockAuthenticationDaoUserMarissaWithSalt());
provider.setSaltSource(salt);
provider.setUserCache(new MockUserCache());
Authentication result = provider.authenticate(token);
if (!(result instanceof DaoAuthenticationToken)) {
if (!(result instanceof UsernamePasswordAuthenticationToken)) {
fail(
"Should have returned instance of DaoPasswordAuthenticationToken");
"Should have returned instance of UsernamePasswordAuthenticationToken");
}
DaoAuthenticationToken castResult = (DaoAuthenticationToken) result;
UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;
assertEquals("marissa", castResult.getPrincipal());
assertEquals("koala{SYSTEM_SALT_VALUE}", castResult.getCredentials());
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
assertEquals(provider.getKey().hashCode(), castResult.getKeyHash());
}
public void testDaoAuthenticationTokensThatHaveExpiredAreRefreshed()
throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("marissa",
"koala");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setKey("x");
provider.setRefreshTokenInterval(0); // never cache
provider.setAuthenticationDao(new MockAuthenticationDaoUserMarissa());
Authentication result = provider.authenticate(token);
if (!(result instanceof DaoAuthenticationToken)) {
fail("Should have returned instance of DaoAuthenticationToken");
}
DaoAuthenticationToken castResult = (DaoAuthenticationToken) result;
assertEquals("marissa", castResult.getPrincipal());
assertEquals(provider.getKey().hashCode(), castResult.getKeyHash());
Thread.sleep(1000);
assertTrue(castResult.getExpires().before(new Date())); // already expired
// Now try to re-authenticate
Authentication secondResult = provider.authenticate(result);
if (!(secondResult instanceof DaoAuthenticationToken)) {
fail("Should have returned instance of DaoAuthenticationToken");
}
// Should still have a later expiry time than original
assertTrue(castResult.getExpires().before(((DaoAuthenticationToken) secondResult)
.getExpires()));
}
public void testDaoAuthenticationTokensWithWrongKeyAreRejected()
throws Exception {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setKey("x");
provider.setRefreshTokenInterval(0); // never cache
provider.setAuthenticationDao(new MockAuthenticationDaoUserMarissa());
DaoAuthenticationToken token = new DaoAuthenticationToken("key",
new Date(), "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
try {
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
} catch (BadCredentialsException expected) {
assertTrue(true);
}
}
public void testGettersSetters() {
@@ -293,12 +207,15 @@ public class DaoAuthenticationProviderTests extends TestCase {
provider.setSaltSource(new SystemWideSaltSource());
assertEquals(SystemWideSaltSource.class,
provider.getSaltSource().getClass());
provider.setUserCache(new EhCacheBasedUserCache());
assertEquals(EhCacheBasedUserCache.class,
provider.getUserCache().getClass());
}
public void testStartupFailsIfNoAuthenticationDao()
throws Exception {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setKey("xxx");
try {
provider.afterPropertiesSet();
@@ -308,9 +225,11 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
public void testStartupFailsIfNoKeySet() throws Exception {
public void testStartupFailsIfNoUserCacheSet() throws Exception {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setAuthenticationDao(new MockAuthenticationDaoUserMarissa());
assertEquals(NullUserCache.class, provider.getUserCache().getClass());
provider.setUserCache(null);
try {
provider.afterPropertiesSet();
@@ -323,8 +242,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
public void testStartupSuccess() throws Exception {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
AuthenticationDao dao = new MockAuthenticationDaoUserMarissa();
provider.setKey("x");
provider.setAuthenticationDao(dao);
provider.setUserCache(new MockUserCache());
assertEquals(dao, provider.getAuthenticationDao());
provider.afterPropertiesSet();
assertTrue(true);
@@ -334,7 +253,6 @@ public class DaoAuthenticationProviderTests extends TestCase {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
assertTrue(provider.supports(UsernamePasswordAuthenticationToken.class));
assertTrue(!provider.supports(TestingAuthenticationToken.class));
assertTrue(provider.supports(DaoAuthenticationToken.class));
}
//~ Inner Classes ==========================================================
@@ -390,4 +308,16 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
}
private class MockUserCache implements UserCache {
private Map cache = new HashMap();
public User getUserFromCache(String username) {
return (User) cache.get(username);
}
public void putUserInCache(User user) {
cache.put(user.getUsername(), user);
}
}
}

View File

@@ -1,226 +0,0 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.providers.dao;
import junit.framework.TestCase;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import java.util.Date;
/**
* Tests {@link DaoAuthenticationToken}.
*
* @author Ben Alex
* @version $Id$
*/
public class DaoAuthenticationTokenTests extends TestCase {
//~ Constructors ===========================================================
public DaoAuthenticationTokenTests() {
super();
}
public DaoAuthenticationTokenTests(String arg0) {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(DaoAuthenticationTokenTests.class);
}
public void testConstructorRejectsNulls() {
try {
new DaoAuthenticationToken(null, new Date(), "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new DaoAuthenticationToken("key", null, "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new DaoAuthenticationToken("key", new Date(), null, "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new DaoAuthenticationToken("key", new Date(), "Test", null,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new DaoAuthenticationToken("key", new Date(), "Test", "Password",
null);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new DaoAuthenticationToken("key", new Date(), "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), null});
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testEqualsWhenEqual() {
Date date = new Date();
DaoAuthenticationToken token1 = new DaoAuthenticationToken("key", date,
"Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
DaoAuthenticationToken token2 = new DaoAuthenticationToken("key", date,
"Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
assertEquals(token1, token2);
}
public void testGetters() {
Date date = new Date();
DaoAuthenticationToken token = new DaoAuthenticationToken("key", date,
"Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
assertEquals("key".hashCode(), token.getKeyHash());
assertEquals("Test", token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertEquals("ROLE_ONE", token.getAuthorities()[0].getAuthority());
assertEquals("ROLE_TWO", token.getAuthorities()[1].getAuthority());
assertEquals(date, token.getExpires());
}
public void testNoArgConstructor() {
try {
new DaoAuthenticationToken();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testNotEqualsDueToAbstractParentEqualsCheck() {
Date date = new Date();
DaoAuthenticationToken token1 = new DaoAuthenticationToken("key", date,
"Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
DaoAuthenticationToken token2 = new DaoAuthenticationToken("key", date,
"DIFFERENT_PRINCIPAL", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
assertTrue(!token1.equals(token2));
}
public void testNotEqualsDueToDifferentAuthenticationClass() {
DaoAuthenticationToken token1 = new DaoAuthenticationToken("key",
new Date(), "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")});
token2.setAuthenticated(true);
assertTrue(!token1.equals(token2));
}
public void testNotEqualsDueToDifferentExpiresDate() {
DaoAuthenticationToken token1 = new DaoAuthenticationToken("key",
new Date(50000), "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
DaoAuthenticationToken token2 = new DaoAuthenticationToken("key",
new Date(60000), "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
assertTrue(!token1.equals(token2));
}
public void testNotEqualsDueToKey() {
Date date = new Date();
DaoAuthenticationToken token1 = new DaoAuthenticationToken("key", date,
"Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
DaoAuthenticationToken token2 = new DaoAuthenticationToken("DIFFERENT_KEY",
date, "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
assertTrue(!token1.equals(token2));
}
public void testSetAuthenticatedIgnored() {
DaoAuthenticationToken token = new DaoAuthenticationToken("key",
new Date(), "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
assertTrue(token.isAuthenticated());
token.setAuthenticated(false); // ignored
assertTrue(token.isAuthenticated());
}
public void testToString() {
DaoAuthenticationToken token = new DaoAuthenticationToken("key",
new Date(), "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
String result = token.toString();
assertTrue(result.lastIndexOf("Expires:") != -1);
}
}

View File

@@ -0,0 +1,83 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.providers.dao.cache;
import junit.framework.TestCase;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.providers.dao.User;
/**
* Tests {@link EhCacheBasedUserCache}.
*
* @author Ben Alex
* @version $Id$
*/
public class EhCacheBasedUserCacheTests extends TestCase {
//~ Constructors ===========================================================
public EhCacheBasedUserCacheTests() {
super();
}
public EhCacheBasedUserCacheTests(String arg0) {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(EhCacheBasedUserCacheTests.class);
}
public void testCacheOperation() throws Exception {
EhCacheBasedUserCache cache = new EhCacheBasedUserCache();
cache.afterPropertiesSet();
// Check it gets stored in the cache
cache.putUserInCache(getUser());
assertEquals(getUser().getPassword(),
cache.getUserFromCache(getUser().getUsername()).getPassword());
// Check it gets removed from the cache
cache.removeUserFromCache(getUser());
assertNull(cache.getUserFromCache(getUser().getUsername()));
// Check it doesn't return values for null or unknown users
assertNull(cache.getUserFromCache(null));
assertNull(cache.getUserFromCache("UNKNOWN_USER"));
cache.destroy();
}
public void testGettersSetters() {
EhCacheBasedUserCache cache = new EhCacheBasedUserCache();
cache.setMinutesToIdle(15);
assertEquals(15, cache.getMinutesToIdle());
}
private User getUser() {
return new User("john", "password", true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
}
}

View File

@@ -0,0 +1,63 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.providers.dao.cache;
import junit.framework.TestCase;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.providers.dao.User;
/**
* Tests {@link NullUserCache}.
*
* @author Ben Alex
* @version $Id$
*/
public class NullUserCacheTests extends TestCase {
//~ Constructors ===========================================================
public NullUserCacheTests() {
super();
}
public NullUserCacheTests(String arg0) {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(NullUserCacheTests.class);
}
public void testCacheOperation() throws Exception {
NullUserCache cache = new NullUserCache();
cache.putUserInCache(getUser());
assertNull(cache.getUserFromCache(null));
}
private User getUser() {
return new User("john", "password", true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
}
}

View File

@@ -36,7 +36,6 @@
<!-- Authentication provider that queries our data access object -->
<bean id="daoAuthenticationProvider" class="net.sf.acegisecurity.providers.dao.DaoAuthenticationProvider">
<property name="authenticationDao"><ref bean="inMemoryDaoImpl"/></property>
<property name="key"><value>my_password</value></property>
</bean>
<!-- The authentication manager that iterates through our only authentication provider -->