View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.shiro.mgt;
20  
21  import org.apache.shiro.SecurityUtils;
22  import org.apache.shiro.authc.AuthenticationToken;
23  import org.apache.shiro.authc.UsernamePasswordToken;
24  import org.apache.shiro.config.Ini;
25  import org.apache.shiro.realm.text.IniRealm;
26  import org.apache.shiro.subject.Subject;
27  import org.apache.shiro.util.ThreadContext;
28  import org.junit.After;
29  import org.junit.Before;
30  import org.junit.Test;
31  
32  import static org.junit.Assert.assertTrue;
33  
34  
35  /**
36   * @since May 8, 2008 12:26:23 AM
37   */
38  public class VMSingletonDefaultSecurityManagerTest {
39  
40      @Before
41      public void setUp() {
42          ThreadContext.remove();
43      }
44  
45      @After
46      public void tearDown() {
47          ThreadContext.remove();
48      }
49  
50      @Test
51      public void testVMSingleton() {
52          DefaultSecurityManager sm = new DefaultSecurityManager();
53          Ini ini = new Ini();
54          Ini.Section section = ini.addSection(IniRealm.USERS_SECTION_NAME);
55          section.put("guest", "guest");
56          sm.setRealm(new IniRealm(ini));
57          SecurityUtils.setSecurityManager(sm);
58  
59          try {
60              Subject subject = SecurityUtils.getSubject();
61  
62              AuthenticationToken token = new UsernamePasswordToken("guest", "guest");
63              subject.login(token);
64              subject.getSession().setAttribute("key", "value");
65              assertTrue(subject.getSession().getAttribute("key").equals("value"));
66  
67              subject = SecurityUtils.getSubject();
68  
69              assertTrue(subject.isAuthenticated());
70              assertTrue(subject.getSession().getAttribute("key").equals("value"));
71          } finally {
72              sm.destroy();
73              //SHIRO-270:
74              SecurityUtils.setSecurityManager(null);
75          }
76      }
77  }