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.authz.AuthorizationException;
23 import org.apache.shiro.realm.Realm;
24 import org.apache.shiro.realm.text.TextConfigurationRealm;
25 import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
26 import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
27 import org.apache.shiro.subject.Subject;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.springframework.boot.SpringApplication;
31 import org.springframework.boot.autoconfigure.SpringBootApplication;
32 import org.springframework.context.annotation.Bean;
33 import org.springframework.context.annotation.Configuration;
34 import org.springframework.http.HttpStatus;
35 import org.springframework.ui.Model;
36 import org.springframework.web.bind.annotation.ControllerAdvice;
37 import org.springframework.web.bind.annotation.ExceptionHandler;
38 import org.springframework.web.bind.annotation.ModelAttribute;
39 import org.springframework.web.bind.annotation.ResponseStatus;
40
41 import java.util.HashMap;
42 import java.util.Map;
43
44 @Configuration
45 @ControllerAdvice
46 @SpringBootApplication
47 public class WebApp {
48
49 private static Logger log = LoggerFactory.getLogger(WebApp.class);
50
51 public static void main(String[] args) {
52
53 SpringApplication.run(WebApp.class, args);
54 }
55
56 @ExceptionHandler(AuthorizationException.class)
57 @ResponseStatus(HttpStatus.FORBIDDEN)
58 public String handleException(AuthorizationException e, Model model) {
59
60
61
62 log.debug("AuthorizationException was thrown", e);
63
64 Map<String, Object> map = new HashMap<String, Object>();
65 map.put("status", HttpStatus.FORBIDDEN.value());
66 map.put("message", "No message available");
67 model.addAttribute("errors", map);
68
69 return "error";
70 }
71
72 @Bean
73 public Realm realm() {
74 TextConfigurationRealm realm = new TextConfigurationRealm();
75 realm.setUserDefinitions("joe.coder=password,user\n" +
76 "jill.coder=password,admin");
77
78 realm.setRoleDefinitions("admin=read,write\n" +
79 "user=read");
80 realm.setCachingEnabled(true);
81 return realm;
82 }
83
84 @Bean
85 public ShiroFilterChainDefinition shiroFilterChainDefinition() {
86 DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
87 chainDefinition.addPathDefinition("/login.html", "authc");
88 chainDefinition.addPathDefinition("/logout", "logout");
89 return chainDefinition;
90 }
91
92 @ModelAttribute(name = "subject")
93 public Subject subject() {
94 return SecurityUtils.getSubject();
95 }
96 }