⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 daoauthenticationprovidertests.java

📁 acegi构造安全的java系统
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
    public void testAuthenticatesASecondTime() {        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("marissa", "koala");        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();        provider.setUserDetailsService(new MockAuthenticationDaoUserMarissa());        provider.setUserCache(new MockUserCache());        Authentication result = provider.authenticate(token);        if (!(result instanceof UsernamePasswordAuthenticationToken)) {            fail("Should have returned instance of UsernamePasswordAuthenticationToken");        }        // Now try to authenticate with the previous result (with its UserDetails)        Authentication result2 = provider.authenticate(result);        if (!(result2 instanceof UsernamePasswordAuthenticationToken)) {            fail("Should have returned instance of UsernamePasswordAuthenticationToken");        }        assertEquals(result.getCredentials(), result2.getCredentials());    }    public void testAuthenticatesWhenASaltIsUsed() {        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("marissa", "koala");        SystemWideSaltSource salt = new SystemWideSaltSource();        salt.setSystemWideSalt("SYSTEM_SALT_VALUE");        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();        provider.setUserDetailsService(new MockAuthenticationDaoUserMarissaWithSalt());        provider.setSaltSource(salt);        provider.setUserCache(new MockUserCache());        Authentication result = provider.authenticate(token);        if (!(result instanceof UsernamePasswordAuthenticationToken)) {            fail("Should have returned instance of UsernamePasswordAuthenticationToken");        }        UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;        assertEquals(User.class, castResult.getPrincipal().getClass());        // We expect original credentials user submitted to be returned        assertEquals("koala", castResult.getCredentials());        assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());        assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());    }    public void testAuthenticatesWithForcePrincipalAsString() {        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("marissa", "koala");        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();        provider.setUserDetailsService(new MockAuthenticationDaoUserMarissa());        provider.setUserCache(new MockUserCache());        provider.setForcePrincipalAsString(true);        Authentication result = provider.authenticate(token);        if (!(result instanceof UsernamePasswordAuthenticationToken)) {            fail("Should have returned instance of UsernamePasswordAuthenticationToken");        }        UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;        assertEquals(String.class, castResult.getPrincipal().getClass());        assertEquals("marissa", castResult.getPrincipal());    }    public void testDetectsNullBeingReturnedFromAuthenticationDao() {        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("marissa", "koala");        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();        provider.setUserDetailsService(new MockAuthenticationDaoReturnsNull());        try {            provider.authenticate(token);            fail("Should have thrown AuthenticationServiceException");        } catch (AuthenticationServiceException expected) {            assertEquals("UserDetailsService returned null, which is an interface contract violation",                expected.getMessage());        }    }    public void testGettersSetters() {        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();        provider.setPasswordEncoder(new ShaPasswordEncoder());        assertEquals(ShaPasswordEncoder.class, provider.getPasswordEncoder().getClass());        provider.setSaltSource(new SystemWideSaltSource());        assertEquals(SystemWideSaltSource.class, provider.getSaltSource().getClass());        provider.setUserCache(new EhCacheBasedUserCache());        assertEquals(EhCacheBasedUserCache.class, provider.getUserCache().getClass());        assertFalse(provider.isForcePrincipalAsString());        provider.setForcePrincipalAsString(true);        assertTrue(provider.isForcePrincipalAsString());    }    public void testGoesBackToAuthenticationDaoToObtainLatestPasswordIfCachedPasswordSeemsIncorrect() {        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("marissa", "koala");        MockAuthenticationDaoUserMarissa authenticationDao = new MockAuthenticationDaoUserMarissa();        MockUserCache cache = new MockUserCache();        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();        provider.setUserDetailsService(authenticationDao);        provider.setUserCache(cache);        // This will work, as password still "koala"        provider.authenticate(token);        // Check "marissa = koala" ended up in the cache        assertEquals("koala", cache.getUserFromCache("marissa").getPassword());        // Now change the password the AuthenticationDao will return        authenticationDao.setPassword("easternLongNeckTurtle");        // Now try authentication again, with the new password        token = new UsernamePasswordAuthenticationToken("marissa", "easternLongNeckTurtle");        provider.authenticate(token);        // To get this far, the new password was accepted        // Check the cache was updated        assertEquals("easternLongNeckTurtle", cache.getUserFromCache("marissa").getPassword());    }    public void testStartupFailsIfNoAuthenticationDao()        throws Exception {        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();        try {            provider.afterPropertiesSet();            fail("Should have thrown IllegalArgumentException");        } catch (IllegalArgumentException expected) {            assertTrue(true);        }    }    public void testStartupFailsIfNoUserCacheSet() throws Exception {        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();        provider.setUserDetailsService(new MockAuthenticationDaoUserMarissa());        assertEquals(NullUserCache.class, provider.getUserCache().getClass());        provider.setUserCache(null);        try {            provider.afterPropertiesSet();            fail("Should have thrown IllegalArgumentException");        } catch (IllegalArgumentException expected) {            assertTrue(true);        }    }    public void testStartupSuccess() throws Exception {        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();        UserDetailsService userDetailsService = new MockAuthenticationDaoUserMarissa();        provider.setUserDetailsService(userDetailsService);        provider.setUserCache(new MockUserCache());        assertEquals(userDetailsService, provider.getUserDetailsService());        provider.afterPropertiesSet();        assertTrue(true);    }    public void testSupports() {        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();        assertTrue(provider.supports(UsernamePasswordAuthenticationToken.class));        assertTrue(!provider.supports(TestingAuthenticationToken.class));    }    //~ Inner Classes ==================================================================================================    private class MockAuthenticationDaoReturnsNull implements UserDetailsService {        public UserDetails loadUserByUsername(String username)            throws UsernameNotFoundException, DataAccessException {            return null;        }    }    private class MockAuthenticationDaoSimulateBackendError implements UserDetailsService {        public UserDetails loadUserByUsername(String username)            throws UsernameNotFoundException, DataAccessException {            throw new DataRetrievalFailureException("This mock simulator is designed to fail");        }    }    private class MockAuthenticationDaoUserMarissa implements UserDetailsService {        private String password = "koala";        public UserDetails loadUserByUsername(String username)            throws UsernameNotFoundException, DataAccessException {            if ("marissa".equals(username)) {                return new User("marissa", password, true, true, true, true,                    new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});            } else {                throw new UsernameNotFoundException("Could not find: " + username);            }        }        public void setPassword(String password) {            this.password = password;        }    }    private class MockAuthenticationDaoUserMarissaWithSalt implements UserDetailsService {        public UserDetails loadUserByUsername(String username)            throws UsernameNotFoundException, DataAccessException {            if ("marissa".equals(username)) {                return new User("marissa", "koala{SYSTEM_SALT_VALUE}", true, true, true, true,                    new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});            } else {                throw new UsernameNotFoundException("Could not find: " + username);            }        }    }    private class MockAuthenticationDaoUserPeter implements UserDetailsService {        public UserDetails loadUserByUsername(String username)            throws UsernameNotFoundException, DataAccessException {            if ("peter".equals(username)) {                return new User("peter", "opal", false, true, true, true,                    new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});            } else {                throw new UsernameNotFoundException("Could not find: " + username);            }        }    }    private class MockAuthenticationDaoUserPeterAccountExpired implements UserDetailsService {        public UserDetails loadUserByUsername(String username)            throws UsernameNotFoundException, DataAccessException {            if ("peter".equals(username)) {                return new User("peter", "opal", true, false, true, true,                    new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});            } else {                throw new UsernameNotFoundException("Could not find: " + username);            }        }    }    private class MockAuthenticationDaoUserPeterAccountLocked implements UserDetailsService {        public UserDetails loadUserByUsername(String username)            throws UsernameNotFoundException, DataAccessException {            if ("peter".equals(username)) {                return new User("peter", "opal", true, true, true, false,                    new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});            } else {                throw new UsernameNotFoundException("Could not find: " + username);            }        }    }    private class MockAuthenticationDaoUserPeterCredentialsExpired implements UserDetailsService {        public UserDetails loadUserByUsername(String username)            throws UsernameNotFoundException, DataAccessException {            if ("peter".equals(username)) {                return new User("peter", "opal", true, true, false, true,                    new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});            } else {                throw new UsernameNotFoundException("Could not find: " + username);            }        }    }    private class MockUserCache implements UserCache {        private Map cache = new HashMap();        public UserDetails getUserFromCache(String username) {            return (User) cache.get(username);        }        public void putUserInCache(UserDetails user) {            cache.put(user.getUsername(), user);        }        public void removeUserFromCache(String username) {}    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -