1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 import org.apache.shiro.SecurityUtils;
21 import org.apache.shiro.authc.*;
22 import org.apache.shiro.env.BasicIniEnvironment;
23 import org.apache.shiro.ini.IniSecurityManagerFactory;
24 import org.apache.shiro.mgt.SecurityManager;
25 import org.apache.shiro.session.Session;
26 import org.apache.shiro.subject.Subject;
27 import org.apache.shiro.lang.util.Factory;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31
32
33
34
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
44
45
46
47
48
49
50 SecurityManager securityManager = new BasicIniEnvironment("classpath:shiro.ini").getSecurityManager();
51
52
53
54
55
56
57
58 SecurityUtils.setSecurityManager(securityManager);
59
60
61
62
63 Subject currentUser = SecurityUtils.getSubject();
64
65
66 Session session = currentUser.getSession();
67 session.setAttribute("someKey", "aValue");
68 String value = (String) session.getAttribute("someKey");
69 if (value.equals("aValue")) {
70 log.info("Retrieved the correct value! [" + value + "]");
71 }
72
73
74 if (!currentUser.isAuthenticated()) {
75 UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
76 token.setRememberMe(true);
77 try {
78 currentUser.login(token);
79 } catch (UnknownAccountException uae) {
80 log.info("There is no user with username of " + token.getPrincipal());
81 } catch (IncorrectCredentialsException ice) {
82 log.info("Password for account " + token.getPrincipal() + " was incorrect!");
83 } catch (LockedAccountException lae) {
84 log.info("The account for username " + token.getPrincipal() + " is locked. " +
85 "Please contact your administrator to unlock it.");
86 }
87
88 catch (AuthenticationException ae) {
89
90 }
91 }
92
93
94
95 log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
96
97
98 if (currentUser.hasRole("schwartz")) {
99 log.info("May the Schwartz be with you!");
100 } else {
101 log.info("Hello, mere mortal.");
102 }
103
104
105 if (currentUser.isPermitted("lightsaber:wield")) {
106 log.info("You may use a lightsaber ring. Use it wisely.");
107 } else {
108 log.info("Sorry, lightsaber rings are for schwartz masters only.");
109 }
110
111
112 if (currentUser.isPermitted("winnebago:drive:eagle5")) {
113 log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
114 "Here are the keys - have fun!");
115 } else {
116 log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
117 }
118
119
120 currentUser.logout();
121
122 System.exit(0);
123 }
124 }