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