springboot整合Shiro
Apache Shiro是一個功能強大且易于使用的Java安全框架,它執行身份驗證、授權、加密和會話管理。借助Shiro易于理解的API,您可以快速輕松地保護任何應用程序—從最小的移動應用程序到最大的web和企業應用程序。
Shiro的三大核心概念Subject:
主體,代表了當前“用戶”,這個用戶不一定是一個具體的人,與當前應用交互的任何東西都是Subject,如爬蟲、機器人等;即一個抽象概念;所有Subject都綁定到SecurityManager,與Subject的所有交互都會委托給SecurityManager;可以把Subject認為是一個門面;SecurityManager才是實際的執行者。
SecurityManager:
安全管理器;即所有與安全有關的操作都會與SecurityManager交互;且它管理著所有Subject;可以看出它是shiro的核心, SecurityManager相當于spring mvc中的dispatcherServlet前端控制器。
Realm:
域,shiro從Realm獲取安全數據(如用戶、角色、權限),就是說SecurityManager要驗證用戶身份,那么它需要從Realm獲取相應的用戶進行比較以確定用戶身份是否合法;也需要從Realm得到用戶相應的角色/權限進行驗證用戶是否能進行操作;可以把Realm看成DataSource,即安全數據源。
Shiro功能介紹Authentication:
身份認證/登錄,驗證用戶是不是擁有相應的身份;
Authorization:
授權,即權限驗證,驗證某個已認證的用戶是否擁有某個權限;即判斷用 戶是否能進行什么操作,如:驗證某個用戶是否擁有某個角色?;蛘呒毩6鹊尿炞C某個用戶對某個資源是否具有某個權限
Session Manager:
會話管理,即用戶登錄后就是一次會話,在沒有退出之前,它的所有信息都在會話中;會話可以是普通 JavaSE 環境,也可以是 Web 環境的
Cryptography:
加密,保護數據的安全性,如密碼加密存儲到數據庫,而不是明文存儲; Web Support:Web 支持,可以非常容易的集成到Web 環境;
Caching:
緩存,比如用戶登錄后,其用戶信息、擁有的角色/權限不必每次去查,這樣可以提高效率;
Concurrency:
Shiro 支持多線程應用的并發驗證,即如在一個線程中開啟另一個線程,能把權限自動傳播過去;
Testing:
提供測試支持;
Run As:
允許一個用戶假裝為另一個用戶(如果他們允許)的身份進行訪問;
Remember Me:
記住我,這個是非常常見的功能,即一次登錄后,下次再來的話不用登錄了
Springboot整合Shiro導入依賴<!-- 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
常用攔截器分類說明
@Configurationpublic 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');*///授權filterChainDefinitionMap.put('/user/add','perms[user:add]');filterChainDefinitionMap.put('/user/update','perms[user:update]');//設置登錄的請求filterFactoryBean.setLoginUrl('/toLogin');//設置未授權頁面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
創建UserRealm繼承AuthorizingRealm實現doGetAuthorizationInfo()、doGetAuthenticationInfo()方法
從數據庫中拿到用戶信息,這里需要整合MyBatis、Druid相關依賴,具體的springboot整合MyBatis的代碼這里就贅述了,如果自己聯系,可以不從數據庫中獲取數據,可以自己直接設定默認的username和password
perm是該用戶的權限可以通過authorizationInfo.addStringPermissions();方法授權
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('執行了======>授權');return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println('執行了======>認證');UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;User user = userService.getByUsername(token.getUsername());if (user == null) { return null;}//密碼可以加密//密碼認證,shiro加密return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),''); }}Controller
@Controllerpublic 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 '未經授權'; } @RequestMapping('/logout') public String logout() {return '/login'; }}
前端頁面這里就不獻丑了,大家自由發揮
Shiro整合thymeleaf導入依賴<!--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=''> <!--沒有認證不顯示--> <p><button><a th:href='http://www.intensediesel.com/bcjs/@{/toLogin}'>登錄</a></button></p></div><div shiro:authenticated=''><!--認證了顯示--> <p><button><a th:href='http://www.intensediesel.com/bcjs/@{/logout}'>退出</a></button></p></div><hr/><div shiro:hasPermission='user:update'><!--有user:update 權限顯示--> <a th:href='http://www.intensediesel.com/bcjs/@{/user/add}'>add</a></div><div shiro:hasPermission='user:add'><!--有user:add權限顯示--> <a th:href='http://www.intensediesel.com/bcjs/@{/user/update}'>update</a></div>總結
本篇文章就到這里了,希望能對你有所幫助,也希望您能夠多多關注好吧啦網的更多內容!
相關文章: