SpringBoot整合Shiro實現(xiàn)登錄認證的方法
安全無處不在,趁著放假讀了一下 Shiro 文檔,并記錄一下 Shiro 整合 Spring Boot 在數(shù)據(jù)庫中根據(jù)角色控制訪問權限
簡介
Apache Shiro是一個功能強大、靈活的,開源的安全框架。它可以干凈利落地處理身份驗證、授權、企業(yè)會話管理和加密。
上圖是 Shiro 的基本架構
Authentication(認證)
有時被稱為“登錄”,用來證明用戶是用戶他們自己本人
Authorization(授權)
訪問控制的過程,即確定“誰”訪問“什么”
Session Management(會話管理)
管理用戶特定的會話,在 Shiro 里面可以發(fā)現(xiàn)所有的用戶的會話信息都會由 Shiro 來進行控制
Cryptography(加密)
在對數(shù)據(jù)源使用加密算法加密的同時,保證易于使用
Start
環(huán)境
Spring Boot 1.5.9 MySQL 5.7 Maven 3.5.2 Spring Data Jpa Lombok
添加依賴
這里只給出主要的 Shiro 依賴
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-starter</artifactId> <version>1.4.0-RC2</version> </dependency>
配置
我們暫時只需要用戶表、角色表,在 Spring boot 中修改配置文件將自動為我們創(chuàng)建數(shù)據(jù)庫表
server: port: 8888 spring: datasource: driver-class-name: com.mysql.jdbc.Driver username: root password: root url: jdbc:mysql://localhost:3306/shiro?characterEncoding=utf-8&useSSL=false jpa: generate-ddl: true hibernate: ddl-auto: update show-sql: true
實體
Role.java
@Data @Entity public class Role { @Id @GeneratedValue private Integer id; private Long userId; private String role; }
User.java
@Data @Entity public class User { @Id @GeneratedValue private Long id; private String username; private String password; }
Realm
首先建立 Realm 類,繼承自 AuthorizingRealm,自定義我們自己的授權和認證的方法。Realm 是可以訪問特定于應用程序的安全性數(shù)據(jù)(如用戶,角色和權限)的組件。
Realm.java
public class Realm extends AuthorizingRealm { @Autowired private UserService userService; //授權 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { //從憑證中獲得用戶名 String username = (String) SecurityUtils.getSubject().getPrincipal(); //根據(jù)用戶名查詢用戶對象 User user = userService.getUserByUserName(username); //查詢用戶擁有的角色 List<Role> list = roleService.findByUserId(user.getId()); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); for (Role role : list) { //賦予用戶角色 info.addStringPermission(role.getRole()); } return info; } //認證 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { //獲得當前用戶的用戶名 String username = (String) authenticationToken.getPrincipal(); //從數(shù)據(jù)庫中根據(jù)用戶名查找用戶 User user = userService.getUserByUserName(username); if (userService.getUserByUserName(username) == null) { throw new UnknownAccountException( "沒有在本系統(tǒng)中找到對應的用戶信息。"); } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),getName()); return info; } }
Shiro 配置類
ShiroConfig.java
@Configuration public class ShiroConfig { @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); //以下是過濾鏈,按順序過濾,所以/**需要放最后 //開放的靜態(tài)資源 filterChainDefinitionMap.put("/favicon.ico", "anon");//網(wǎng)站圖標 filterChainDefinitionMap.put("/**", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } @Bean public DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(myRealm()); return defaultWebSecurityManager; } @Bean public MyRealm myRealm() { MyRealm myRealm = new MyRealm(); return myRealm; } }
控制器
UserController.java
@Controller public class UserController { @Autowired private UserService userService; @GetMapping("/") public String index() { return "index"; } @GetMapping("/login") public String toLogin() { return "login"; } @GetMapping("/admin") public String admin() { return "admin"; } @PostMapping("/login") public String doLogin(String username, String password) { UsernamePasswordToken token = new UsernamePasswordToken(username, password); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); } catch (Exception e) { e.printStackTrace(); } return "redirect:admin"; } @GetMapping("/home") public String home() { Subject subject = SecurityUtils.getSubject(); try { subject.checkPermission("admin"); } catch (UnauthorizedException exception) { System.out.println("沒有足夠的權限"); } return "home"; } @GetMapping("/logout") public String logout() { return "index"; } }
Service
UserService.java
@Service public class UserService { @Autowired private UserDao userDao; public User getUserByUserName(String username) { return userDao.findByUsername(username); } @RequiresRoles("admin") public void send() { System.out.println("我現(xiàn)在擁有角色admin,可以執(zhí)行本條語句"); } }
展示層
admin.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <html lang="en"/> <head> <meta charset="UTF-8"/> <title>Title</title> </head> <body> <form action="/login" method="post"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="submit" value="登錄" /> </form> </body> </html>
home.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <html lang="en"/> <head> <meta charset="UTF-8"/> <title>Title</title> </head> <body> home </body> </html>
index.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <html lang="en"/> <head> <meta charset="UTF-8"/> <title>Title</title> </head> <body> index <a href="/login" rel="external nofollow" >請登錄</a> </body> </html>
login.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <html lang="en"/> <head> <meta charset="UTF-8"/> <title>Title</title> </head> <body> <form action="/login" method="post"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="submit" value="登錄" /> </form> </body> </html>
總結
這個小案例實現(xiàn)了根據(jù)角色來控制用戶訪問,其中最重要的就是 Realm,它充當了Shiro與應用安全數(shù)據(jù)間的“橋梁”或者“連接器”
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- SpringBoot+Shiro+Redis+Mybatis-plus 實戰(zhàn)項目及問題小結
- 解決springboot+shiro 權限攔截失效的問題
- Springboot和bootstrap實現(xiàn)shiro權限控制配置過程
- SpringBoot + Shiro前后端分離權限
- SpringBoot 整合 Shiro 密碼登錄與郵件驗證碼登錄功能(多 Realm 認證)
- Springboot shiro認證授權實現(xiàn)原理及實例
- 基于springboot實現(xiàn)整合shiro實現(xiàn)登錄認證以及授權過程解析
- Springboot+Shiro+Mybatis+mysql實現(xiàn)權限安全認證的示例代碼
相關文章
Java數(shù)據(jù)結構之優(yōu)先級隊列(堆)圖文詳解
優(yōu)先級隊列是比棧和隊列更專用的結構,在多數(shù)情況下都非常有用,下面這篇文章主要給大家介紹了關于Java數(shù)據(jù)結構之優(yōu)先級隊列(堆)的相關資料,需要的朋友可以參考下2022-03-03Spring Boot通過Redis實現(xiàn)防止重復提交
表單提交是一個非常常見的功能,如果不加控制,容易因為用戶的誤操作或網(wǎng)絡延遲導致同一請求被發(fā)送多次,本文主要介紹了Spring Boot通過Redis實現(xiàn)防止重復提交,具有一定的參考價值,感興趣的可以了解一下2024-06-06Java Web監(jiān)聽器如何實現(xiàn)定時發(fā)送郵件
這篇文章主要介紹了Java Web監(jiān)聽器如何實現(xiàn)定時發(fā)送郵件,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-12-12springboot2+mybatis多種方式實現(xiàn)多數(shù)據(jù)配置方法
這篇文章主要介紹了springboot2+mybatis多種方式實現(xiàn)多數(shù)據(jù)配置方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03Java獲取項目路徑方式System.getProperty(“user.dir“)
這篇文章主要介紹了Java獲取項目路徑方式System.getProperty(“user.dir“),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12