1   /* Copyright 2004, 2005 Acegi Technology Pty Limited
2    *
3    * Licensed under the Apache License, Version 2.0 (the "License");
4    * you may not use this file except in compliance with the License.
5    * You may obtain a copy of the License at
6    *
7    *     http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  
16  package org.acegisecurity.providers;
17  
18  import java.util.List;
19  import java.util.Vector;
20  
21  import junit.framework.TestCase;
22  
23  import org.acegisecurity.Authentication;
24  import org.acegisecurity.AuthenticationException;
25  import org.acegisecurity.AuthenticationServiceException;
26  import org.acegisecurity.GrantedAuthority;
27  import org.acegisecurity.GrantedAuthorityImpl;
28  import org.acegisecurity.concurrent.ConcurrentSessionControllerImpl;
29  import org.acegisecurity.concurrent.NullConcurrentSessionController;
30  import org.springframework.context.ApplicationEvent;
31  import org.springframework.context.ApplicationEventPublisher;
32  
33  
34  /***
35   * Tests {@link ProviderManager}.
36   *
37   * @author Ben Alex
38   * @version $Id: ProviderManagerTests.java,v 1.8 2005/11/30 01:23:34 benalex Exp $
39   */
40  public class ProviderManagerTests extends TestCase {
41      //~ Constructors ===========================================================
42  
43      public ProviderManagerTests() {
44          super();
45      }
46  
47      public ProviderManagerTests(String arg0) {
48          super(arg0);
49      }
50  
51      //~ Methods ================================================================
52  
53      public final void setUp() throws Exception {
54          super.setUp();
55      }
56  
57      public static void main(String[] args) {
58          junit.textui.TestRunner.run(ProviderManagerTests.class);
59      }
60  
61      public void testAuthenticationFails() throws Exception {
62          UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
63                  "Password",
64                  new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
65                          "ROLE_TWO")});
66  
67          ProviderManager mgr = makeProviderManager();
68          mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true));
69  
70          try {
71              mgr.authenticate(token);
72              fail("Should have thrown ProviderNotFoundException");
73          } catch (ProviderNotFoundException expected) {
74              assertTrue(true);
75          }
76      }
77  
78      public void testAuthenticationSuccess() throws Exception {
79          TestingAuthenticationToken token = new TestingAuthenticationToken("Test",
80                  "Password",
81                  new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
82                          "ROLE_TWO")});
83  
84          ProviderManager mgr = makeProviderManager();
85          mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true));
86          Authentication result = mgr.authenticate(token);
87  
88          if (!(result instanceof TestingAuthenticationToken)) {
89              fail("Should have returned instance of TestingAuthenticationToken");
90          }
91  
92          TestingAuthenticationToken castResult = (TestingAuthenticationToken) result;
93          assertEquals("Test", castResult.getPrincipal());
94          assertEquals("Password", castResult.getCredentials());
95          assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());
96          assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
97      }
98  
99      public void testAuthenticationSuccessWhenFirstProviderReturnsNullButSecondAuthenticates() {
100         TestingAuthenticationToken token = new TestingAuthenticationToken("Test",
101                 "Password",
102                 new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
103                         "ROLE_TWO")});
104 
105         ProviderManager mgr = makeProviderManagerWithMockProviderWhichReturnsNullInList();
106         mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true));
107         Authentication result = mgr.authenticate(token);
108 
109         if (!(result instanceof TestingAuthenticationToken)) {
110             fail("Should have returned instance of TestingAuthenticationToken");
111         }
112 
113         TestingAuthenticationToken castResult = (TestingAuthenticationToken) result;
114         assertEquals("Test", castResult.getPrincipal());
115         assertEquals("Password", castResult.getCredentials());
116         assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());
117         assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
118     }
119 
120     public void testConcurrentSessionControllerConfiguration()
121         throws Exception {
122         ProviderManager target = new ProviderManager();
123 
124         //The NullConcurrentSessionController should be the default
125         assertNotNull(target.getSessionController());
126         assertTrue(target.getSessionController() instanceof NullConcurrentSessionController);
127 
128         ConcurrentSessionControllerImpl impl = new ConcurrentSessionControllerImpl();
129         target.setSessionController(impl);
130         assertEquals(impl, target.getSessionController());
131     }
132 
133     public void testStartupFailsIfProviderListDoesNotContainingProviders()
134         throws Exception {
135         List providers = new Vector();
136         providers.add("THIS_IS_NOT_A_PROVIDER");
137 
138         ProviderManager mgr = new ProviderManager();
139 
140         try {
141             mgr.setProviders(providers);
142             fail("Should have thrown IllegalArgumentException");
143         } catch (IllegalArgumentException expected) {
144             assertTrue(true);
145         }
146     }
147 
148     public void testStartupFailsIfProviderListNotSet()
149         throws Exception {
150         ProviderManager mgr = new ProviderManager();
151 
152         try {
153             mgr.afterPropertiesSet();
154             fail("Should have thrown IllegalArgumentException");
155         } catch (IllegalArgumentException expected) {
156             assertTrue(true);
157         }
158     }
159 
160     public void testStartupFailsIfProviderListNull() throws Exception {
161         ProviderManager mgr = new ProviderManager();
162 
163         try {
164             mgr.setProviders(null);
165             fail("Should have thrown IllegalArgumentException");
166         } catch (IllegalArgumentException expected) {
167             assertTrue(true);
168         }
169     }
170 
171     public void testSuccessfulStartup() throws Exception {
172         ProviderManager mgr = makeProviderManager();
173         mgr.afterPropertiesSet();
174         assertTrue(true);
175         assertEquals(1, mgr.getProviders().size());
176     }
177 
178     private ProviderManager makeProviderManager() throws Exception {
179         MockProvider provider1 = new MockProvider();
180         List providers = new Vector();
181         providers.add(provider1);
182 
183         ProviderManager mgr = new ProviderManager();
184         mgr.setProviders(providers);
185         
186         mgr.afterPropertiesSet();
187         return mgr;
188     }
189 
190     private ProviderManager makeProviderManagerWithMockProviderWhichReturnsNullInList() {
191         MockProviderWhichReturnsNull provider1 = new MockProviderWhichReturnsNull();
192         MockProvider provider2 = new MockProvider();
193         List providers = new Vector();
194         providers.add(provider1);
195         providers.add(provider2);
196 
197         ProviderManager mgr = new ProviderManager();
198         mgr.setProviders(providers);
199 
200         return mgr;
201     }
202 
203     //~ Inner Classes ==========================================================
204 
205     private class MockProvider implements AuthenticationProvider {
206         public Authentication authenticate(Authentication authentication)
207             throws AuthenticationException {
208             if (supports(authentication.getClass())) {
209                 return authentication;
210             } else {
211                 throw new AuthenticationServiceException(
212                     "Don't support this class");
213             }
214         }
215 
216         public boolean supports(Class authentication) {
217             if (TestingAuthenticationToken.class.isAssignableFrom(
218                     authentication)) {
219                 return true;
220             } else {
221                 return false;
222             }
223         }
224     }
225 
226     private class MockProviderWhichReturnsNull implements AuthenticationProvider {
227         public Authentication authenticate(Authentication authentication)
228             throws AuthenticationException {
229             if (supports(authentication.getClass())) {
230                 return null;
231             } else {
232                 throw new AuthenticationServiceException(
233                     "Don't support this class");
234             }
235         }
236 
237         public boolean supports(Class authentication) {
238             if (TestingAuthenticationToken.class.isAssignableFrom(
239                     authentication)) {
240                 return true;
241             } else {
242                 return false;
243             }
244         }
245     }
246     
247     private class MockApplicationEventPublisher implements ApplicationEventPublisher {
248 		private boolean expectedEvent;
249     	
250 		public MockApplicationEventPublisher(boolean expectedEvent) {
251 			this.expectedEvent = expectedEvent;
252 		}
253 		
254     	public void publishEvent(ApplicationEvent event) {
255 			if (expectedEvent == false) {
256 				throw new IllegalStateException("The ApplicationEventPublisher did not expect to receive this event");				
257 			}
258 		}
259     }
260 }