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.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 UsernamePasswordTokenen.html#UsernamePasswordToken">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 }
76 catch (AuthorizationException e) {
77 log.info("Subject was NOT allowed to execute method 'writeRestrictedCall'");
78 }
79
80
81 subject.logout();
82 Assert.isTrue(!subject.isAuthenticated());
83 }
84
85
86
87
88
89 @PostConstruct
90 private void initStaticSecurityManager() {
91 SecurityUtils.setSecurityManager(securityManager);
92 }
93 }