1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.shiro.samples;
20
21 import org.apache.shiro.SecurityUtils;
22 import org.apache.shiro.authc.UsernamePasswordToken;
23 import org.apache.shiro.authz.AuthorizationException;
24 import org.apache.shiro.mgt.SecurityManager;
25 import org.apache.shiro.subject.Subject;
26 import org.apache.shiro.lang.util.Assert;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import org.springframework.beans.factory.annotation.Autowired;
30 import org.springframework.stereotype.Component;
31
32 import javax.annotation.PostConstruct;
33
34
35
36
37 @Component
38 public class QuickStart {
39
40 private static Logger log = LoggerFactory.getLogger(QuickStart.class);
41
42 @Autowired
43 private SecurityManager securityManager;
44
45 @Autowired
46 private SimpleService simpleService;
47
48 public void run() {
49
50
51 Subject subject = SecurityUtils.getSubject();
52
53
54 Assert.isTrue(!subject.isAuthenticated());
55
56
57 UsernamePasswordToken token = new UsernamePasswordToken("joe.coder", "password");
58 subject.login(token);
59
60
61 subject.checkRole("user");
62
63
64 Assert.isTrue(!subject.hasRole("admin"));
65
66
67 subject.checkPermission("read");
68
69
70 simpleService.readRestrictedCall();
71
72 try {
73
74 simpleService.writeRestrictedCall();
75 } catch (AuthorizationException e) {
76 log.info("Subject was NOT allowed to execute method 'writeRestrictedCall'");
77 }
78
79
80 subject.logout();
81 Assert.isTrue(!subject.isAuthenticated());
82 }
83
84
85
86
87
88 @PostConstruct
89 private void initStaticSecurityManager() {
90 SecurityUtils.setSecurityManager(securityManager);
91 }
92 }