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  
20  import org.apache.shiro.SecurityUtils;
21  import org.apache.shiro.authc.*;
22  import org.apache.shiro.config.IniSecurityManagerFactory;
23  import org.apache.shiro.mgt.SecurityManager;
24  import org.apache.shiro.session.Session;
25  import org.apache.shiro.subject.Subject;
26  import org.apache.shiro.util.Factory;
27  import org.slf4j.Logger;
28  import org.slf4j.LoggerFactory;
29  
30  
31  /**
32   * Simple Quickstart application showing how to use Shiro's API.
33   *
34   * @since 0.9 RC2
35   */
36  public class Quickstart {
37  
38      private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
39  
40  
41      public static void main(String[] args) {
42  
43          // The easiest way to create a Shiro SecurityManager with configured
44          // realms, users, roles and permissions is to use the simple INI config.
45          // We'll do that by using a factory that can ingest a .ini file and
46          // return a SecurityManager instance:
47  
48          // Use the shiro.ini file at the root of the classpath
49          // (file: and url: prefixes load from files and urls respectively):
50          Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
51          SecurityManager securityManager = factory.getInstance();
52  
53          // for this simple example quickstart, make the SecurityManager
54          // accessible as a JVM singleton.  Most applications wouldn't do this
55          // and instead rely on their container configuration or web.xml for
56          // webapps.  That is outside the scope of this simple quickstart, so
57          // we'll just do the bare minimum so you can continue to get a feel
58          // for things.
59          SecurityUtils.setSecurityManager(securityManager);
60  
61          // Now that a simple Shiro environment is set up, let's see what you can do:
62  
63          // get the currently executing user:
64          Subject currentUser = SecurityUtils.getSubject();
65  
66          // Do some stuff with a Session (no need for a web or EJB container!!!)
67          Session session = currentUser.getSession();
68          session.setAttribute("someKey", "aValue");
69          String value = (String) session.getAttribute("someKey");
70          if (value.equals("aValue")) {
71              log.info("Retrieved the correct value! [" + value + "]");
72          }
73  
74          // let's login the current user so we can check against roles and permissions:
75          if (!currentUser.isAuthenticated()) {
76              UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
77              token.setRememberMe(true);
78              try {
79                  currentUser.login(token);
80              } catch (UnknownAccountException uae) {
81                  log.info("There is no user with username of " + token.getPrincipal());
82              } catch (IncorrectCredentialsException ice) {
83                  log.info("Password for account " + token.getPrincipal() + " was incorrect!");
84              } catch (LockedAccountException lae) {
85                  log.info("The account for username " + token.getPrincipal() + " is locked.  " +
86                          "Please contact your administrator to unlock it.");
87              }
88              // ... catch more exceptions here (maybe custom ones specific to your application?
89              catch (AuthenticationException ae) {
90                  //unexpected condition?  error?
91              }
92          }
93  
94          //say who they are:
95          //print their identifying principal (in this case, a username):
96          log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
97  
98          //test a role:
99          if (currentUser.hasRole("schwartz")) {
100             log.info("May the Schwartz be with you!");
101         } else {
102             log.info("Hello, mere mortal.");
103         }
104 
105         //test a typed permission (not instance-level)
106         if (currentUser.isPermitted("lightsaber:wield")) {
107             log.info("You may use a lightsaber ring.  Use it wisely.");
108         } else {
109             log.info("Sorry, lightsaber rings are for schwartz masters only.");
110         }
111 
112         //a (very powerful) Instance Level permission:
113         if (currentUser.isPermitted("winnebago:drive:eagle5")) {
114             log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
115                     "Here are the keys - have fun!");
116         } else {
117             log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
118         }
119 
120         //all done - log out!
121         currentUser.logout();
122 
123         System.exit(0);
124     }
125 }