簡介:
Apache Shiro 是一一個開源的輕量級的Java安全框架,它提供身份驗證、授權、密碼管理以及會話管理等功能。
相對於Spring Security, Shiro框架更加直觀、易用,同時也能提供健壯的安全性。在傳統的SSM框架中,手動整合Shiro的配置步驟還是比較多的,針對Spring Boot, Shiro 官方提供了shiro-spring-boot-web-starter 用來簡化Shiro 在Spring Boot 中的配置。
pom.xml
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-web-starter</artifactId> //已經依賴spring-boot-web-starter <version>1.4.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>com.github.theborakompanioni</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>2.0.0</version> </dependency>
application.properties
#開啟shiro
shiro.enabled=true #開啟shiro web
shiro.web.enabled=true #登陸地址,默認/login.jsp
shiro.loginUrl=/login #登陸成功地址
shiro.successUrl=/index #未獲授權跳轉地址
shiro.unauthorizedUrl=/unauthorized #是否允許通過url進行會話跟蹤,默認true
shiro.sessionManager.sessionIdUrlRewritingEnabled=true #是否允許通過Cookie實現會話跟蹤
shiro.sessionManager.sessionIdCookieEnabled=true
配置shiro
@Configuration public class ShiroConfig { @Bean public Realm realm() {//添加用戶 TextConfigurationRealm realm = new TextConfigurationRealm(); realm.setUserDefinitions("sang=123,user\n admin=123,admin"); //添加用戶名+密碼+角色 realm.setRoleDefinitions("admin=read,write\n user=read"); //添加權限 return realm; }
@Bean #添加過濾規則
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition(); chainDefinition.addPathDefinition("/login", "anon"); //可以匿名訪問 chainDefinition.addPathDefinition("/doLogin", "anon"); //同上 chainDefinition.addPathDefinition("/logout", "logout"); //注銷登陸 chainDefinition.addPathDefinition("/**", "authc"); //其余請求都需要認證后擦可以訪問 return chainDefinition; } @Bean public ShiroDialect shiroDialect() { //可以在Thymeleaf中使用shiro標簽 return new ShiroDialect(); } }
controller:
@Controller public class UserController {
@GetMapping("/hello")
public String hello() {
return "hello shiro!";
}
@PostMapping("/doLogin") public String doLogin(String username, String password, Model model) { UsernamePasswordToken token = new UsernamePasswordToken(username, password); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); //登陸 } catch (AuthenticationException e) { model.addAttribute("error", "用戶名或密碼輸入錯誤!"); return "login"; } return "redirect:/index"; }
@RequiresRoles("admin") //admin角色 @GetMapping("/admin") public String admin() { return "admin"; }
@RequiresRoles(value = {"admin","user"},logical = Logical.OR) //admin或者user任意一個都可以 @GetMapping("/user") public String user() { return "user"; } }
對於不需要角色就可以訪問的頁面
@Configuration public class WebMvcConfig implements WebMvcConfigurer{ @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/login").setViewName("login"); registry.addViewController("/index").setViewName("index"); registry.addViewController("/unauthorized").setViewName("unauthorized"); } }
全局異常處理:
@ControllerAdvice public class ExceptionController { @ExceptionHandler(AuthorizationException.class) public ModelAndView error(AuthorizationException e) { ModelAndView mv = new ModelAndView("unauthorized"); mv.addObject("error", e.getMessage()); return mv; } }
新建5個頁面:

admin.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>管理員頁面</h1> </body> </html>
index.html
<!DOCTYPE html> <html lang="en" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>Hello, <shiro:principal/></h3> <h3><a href="/logout">注銷登錄</a></h3> <h3><a shiro:hasRole="admin" href="/admin">管理員頁面</a></h3> <h3><a shiro:hasAnyRoles="admin,user" href="/user">普通用戶頁面</a></h3> </body> </html>
login.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <form action="/doLogin" method="post"> <input type="text" name="username"><br> <input type="password" name="password"><br> <div th:text="${error}"></div> <input type="submit" value="登錄"> </form> </div> </body> </html>
unauthorized.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <h3>未獲授權,非法訪問</h3> <h3 th:text="${error}"></h3> </div> </body> </html>
user.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>普通用戶頁面</h1> </body> </html>
訪問http://localhost:8080/login

由於上面的shiro配置,可以匿名訪問
輸入我們在shiro配置的2用戶

sang/123

admin/123

不同角色,權限不一樣,頁面也不一樣
