springboot整合Shiro
什么是Shiro
Apache Shiro是一個功能強(qiáng)大且易于使用的Java安全框架,它執(zhí)行身份驗(yàn)證、授權(quán)、加密和會話管理。借助Shiro易于理解的API,您可以快速輕松地保護(hù)任何應(yīng)用程序—從最小的移動應(yīng)用程序到最大的web和企業(yè)應(yīng)用程序。
Shiro的三大核心概念
Subject:
主體,代表了當(dāng)前“用戶”,這個用戶不一定是一個具體的人,與當(dāng)前應(yīng)用交互的任何東西都是Subject,如爬蟲、機(jī)器人等;即一個抽象概念;所有Subject都綁定到SecurityManager,與Subject的所有交互都會委托給SecurityManager;可以把Subject認(rèn)為是一個門面;SecurityManager才是實(shí)際的執(zhí)行者。
SecurityManager:
安全管理器;即所有與安全有關(guān)的操作都會與SecurityManager交互;且它管理著所有Subject;可以看出它是shiro的核心, SecurityManager相當(dāng)于spring mvc中的dispatcherServlet前端控制器。
Realm:
域,shiro從Realm獲取安全數(shù)據(jù)(如用戶、角色、權(quán)限),就是說SecurityManager要驗(yàn)證用戶身份,那么它需要從Realm獲取相應(yīng)的用戶進(jìn)行比較以確定用戶身份是否合法;也需要從Realm得到用戶相應(yīng)的角色/權(quán)限進(jìn)行驗(yàn)證用戶是否能進(jìn)行操作;可以把Realm看成DataSource,即安全數(shù)據(jù)源。
Shiro功能介紹
Authentication:
身份認(rèn)證/登錄,驗(yàn)證用戶是不是擁有相應(yīng)的身份;
Authorization:
授權(quán),即權(quán)限驗(yàn)證,驗(yàn)證某個已認(rèn)證的用戶是否擁有某個權(quán)限;即判斷用 戶是否能進(jìn)行什么操作,如:驗(yàn)證某個用戶是否擁有某個角色。或者細(xì)粒度的驗(yàn)證某個用戶對某個資源是否具有某個權(quán)限
Session Manager:
會話管理,即用戶登錄后就是一次會話,在沒有退出之前,它的所有信息都在會話中;會話可以是普通 JavaSE 環(huán)境,也可以是 Web 環(huán)境的
Cryptography:
加密,保護(hù)數(shù)據(jù)的安全性,如密碼加密存儲到數(shù)據(jù)庫,而不是明文存儲; Web Support:Web 支持,可以非常容易的集成到Web 環(huán)境;
Caching:
緩存,比如用戶登錄后,其用戶信息、擁有的角色/權(quán)限不必每次去查,這樣可以提高效率;
Concurrency:
Shiro 支持多線程應(yīng)用的并發(fā)驗(yàn)證,即如在一個線程中開啟另一個線程,能把權(quán)限自動傳播過去;
Testing:
提供測試支持;
Run As:
允許一個用戶假裝為另一個用戶(如果他們允許)的身份進(jìn)行訪問;
Remember Me:
記住我,這個是非常常見的功能,即一次登錄后,下次再來的話不用登錄了
Springboot整合Shiro
導(dǎo)入依賴
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.7.1</version> </dependency>
配置javaConfig
三大核心對象ShiroFilterFactoryBean
、DefaultWebSecurityManager
、Realm
常用攔截器分類說明
javaConfig
@Configuration public class ShiroConfig { //ShiroFilterFactoryBean @Bean public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Autowired DefaultWebSecurityManager securityManager) { ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean(); filterFactoryBean.setSecurityManager(securityManager); Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); //攔截 filterChainDefinitionMap.put("/user/add", "authc"); filterChainDefinitionMap.put("/user/update", "authc"); filterChainDefinitionMap.put("/user/*", "authc"); filterChainDefinitionMap.put("/logout", "logout");//退出 /*filterChainDefinitionMap.put("/*","authc");*/ //授權(quán) filterChainDefinitionMap.put("/user/add","perms[user:add]"); filterChainDefinitionMap.put("/user/update","perms[user:update]"); //設(shè)置登錄的請求 filterFactoryBean.setLoginUrl("/toLogin"); //設(shè)置未授權(quán)頁面 filterFactoryBean.setUnauthorizedUrl("/unauth"); filterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return filterFactoryBean; } //DefaultWebSecurityManager @Bean public DefaultWebSecurityManager getDefaultWebSecurityManager(@Autowired UserRealm userRealm) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(userRealm); return securityManager; } //Realm @Bean public UserRealm userRealm() { return new UserRealm(); } }
Realm
創(chuàng)建UserRealm
繼承AuthorizingRealm
實(shí)現(xiàn)doGetAuthorizationInfo()
、doGetAuthenticationInfo()
方法
從數(shù)據(jù)庫中拿到用戶信息,這里需要整合MyBatis、Druid相關(guān)依賴,具體的springboot整合MyBatis的代碼這里就贅述了,如果自己聯(lián)系,可以不從數(shù)據(jù)庫中獲取數(shù)據(jù),可以自己直接設(shè)定默認(rèn)的username和password
perm是該用戶的權(quán)限可以通過authorizationInfo.addStringPermissions();
方法授權(quán)
public class UserRealm extends AuthorizingRealm { @Autowired UserService userService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); //authorizationInfo.addStringPermission("user:add"); Subject currentUser = SecurityUtils.getSubject(); /** * 通過session取值 */ /*Session session = currentUser.getSession(); String username = (String) session.getAttribute("username"); System.out.println(username); User user = userService.getByUsername(username); authorizationInfo.addStringPermission(user.getPerm()); System.out.println(user.getPerm());*/ /** * 通過principal取值 */ String username = (String) currentUser.getPrincipal(); System.out.println(username); User user = userService.getByUsername(username); System.out.println(user.getPerm()); String[] perms = user.getPerm().split(","); ArrayList<String> permList = new ArrayList(); for (String perm : perms) { permList.add(perm); } authorizationInfo.addStringPermissions(permList); System.out.println("執(zhí)行了======>授權(quán)"); return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("執(zhí)行了======>認(rèn)證"); UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; User user = userService.getByUsername(token.getUsername()); if (user == null) { return null; } //密碼可以加密 //密碼認(rèn)證,shiro加密 return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),""); } }
Controller
@Controller public class MyController { @RequestMapping("/toLogin") public String toLogin() { return "login"; } @RequestMapping({"/","/index"}) public String toIndex(Model model) { model.addAttribute("msg","Hello,Shiro"); return "index"; } @RequestMapping("/user/add") public String addUser() { return "user/add"; } @RequestMapping("/user/update") public String updateUser() { return "user/update"; } @PostMapping("/login") public String login(String username, String password, Model model) { UsernamePasswordToken token = new UsernamePasswordToken(username, password); Subject currentUser = SecurityUtils.getSubject(); try { currentUser.login(token); Session session = currentUser.getSession(); session.setAttribute("username", username); return "index"; } catch (UnknownAccountException uae) { model.addAttribute("msg", token.getPrincipal() + "用戶名不匹配"); return "login"; } catch (IncorrectCredentialsException ice) { model.addAttribute("msg", token.getPrincipal() + "密碼錯誤"); return "login"; } } @ResponseBody @RequestMapping("/unauth") public String unAuth() { return "未經(jīng)授權(quán)"; } @RequestMapping("/logout") public String logout() { return "/login"; } }
前端頁面這里就不獻(xiàn)丑了,大家自由發(fā)揮
Shiro整合thymeleaf
導(dǎo)入依賴
<!--thymeleaf shiro整合包--> <!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro --> <dependency> <groupId>com.github.theborakompanioni</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>2.0.0</version> </dependency>
HTML頁面命名空間
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
使用舉例
<div shiro:notAuthenticated=""> <!--沒有認(rèn)證不顯示--> <p><button><a th:href="@{/toLogin}">登錄</a></button></p> </div> <div shiro:authenticated=""><!--認(rèn)證了顯示--> <p><button><a th:href="@{/logout}">退出</a></button></p> </div> <hr/> <div shiro:hasPermission="user:update"><!--有user:update 權(quán)限顯示--> <a th:href="@{/user/add}">add</a> </div> <div shiro:hasPermission="user:add"><!--有user:add權(quán)限顯示--> <a th:href="@{/user/update}">update</a> </div>
總結(jié)
本篇文章就到這里了,希望能對你有所幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
走進(jìn)SpringBoot之配置文件與多環(huán)境詳解
這篇文章主要介紹了走進(jìn)SpringBoot之配置文件與多環(huán)境,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05Spring?Boot日志基礎(chǔ)使用之如何設(shè)置日志級別
這篇文章主要介紹了Spring?Boot日志基礎(chǔ)使用設(shè)置日志級別的方法,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09Springboot實(shí)現(xiàn)前后端分離excel下載
這篇文章主要介紹了Springboot實(shí)現(xiàn)前后端分離excel下載,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11淺析如何在SpringBoot中實(shí)現(xiàn)數(shù)據(jù)脫敏
脫敏是指在不改變原數(shù)據(jù)結(jié)構(gòu)的前提下,通過某種方式處理數(shù)據(jù),使數(shù)據(jù)不能直接暴露用戶的真實(shí)信息,下面我們就來看看SpringBoot中實(shí)現(xiàn)數(shù)據(jù)脫敏的具體方法吧2024-03-03Java畢業(yè)設(shè)計實(shí)戰(zhàn)之在線蛋糕銷售商城的實(shí)現(xiàn)
這是一個使用了java+JSP+Springboot+maven+mysql+ThymeLeaf+FTP開發(fā)的在線蛋糕銷售商城,是一個畢業(yè)設(shè)計的實(shí)戰(zhàn)練習(xí),具有線上蛋糕商城該有的所有功能,感興趣的朋友快來看看吧2022-01-01Java實(shí)戰(zhàn)角色權(quán)限后臺腳手架系統(tǒng)的實(shí)現(xiàn)流程
只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+Springboot+Maven+myBaits-Plus+Vue+Element-UI+Mysql實(shí)現(xiàn)一個角色權(quán)限后臺腳手架系統(tǒng),大家可以在過程中查缺補(bǔ)漏,提升水平2022-01-01基于Java+SpringBoot實(shí)現(xiàn)人臉識別搜索
人臉識別搜索技術(shù)作為現(xiàn)代計算機(jī)視覺領(lǐng)域的重要研究方向之一,已經(jīng)在多個領(lǐng)域展現(xiàn)出巨大的應(yīng)用潛力,隨著信息技術(shù)的飛速發(fā)展,人臉識別搜索在多個領(lǐng)域得到了廣泛關(guān)注和應(yīng)用,本文旨在探討人臉識別搜索技術(shù)的背景、原理以及其在實(shí)際應(yīng)用中的意義和挑戰(zhàn)2023-08-08java.lang.OutOfMemoryError 錯誤整理及解決辦法
這篇文章主要介紹了java.lang.OutOfMemoryError 錯誤整理及解決辦法的相關(guān)資料,需要的朋友可以參考下2016-10-10