Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)
Shiro簡(jiǎn)介
- Apache Shiro是一個(gè)強(qiáng)大且易用的Java安全框架,執(zhí)行身份驗(yàn)證、授權(quán)、密碼和會(huì)話管理
- 三個(gè)核心組件:Subject, SecurityManager 和 Realms
- Subject代表了當(dāng)前用戶(hù)的安全操作
- SecurityManager管理所有用戶(hù)的安全操作,是Shiro框架的核心,Shiro通過(guò)SecurityManager來(lái)管理內(nèi)部組件實(shí)例,并通過(guò)它來(lái)提供安全管理的各種服務(wù)。
- Realm充當(dāng)了Shiro與應(yīng)用安全數(shù)據(jù)間的“橋梁”或者“連接器”。也就是說(shuō),當(dāng)對(duì)用戶(hù)執(zhí)行認(rèn)證(登錄)和授權(quán)(訪問(wèn)控制)驗(yàn)證時(shí),Shiro會(huì)從應(yīng)用配置的Realm中查找用戶(hù)及其權(quán)限信息。
- Realm實(shí)質(zhì)上是一個(gè)安全相關(guān)的DAO:它封裝了數(shù)據(jù)源的連接細(xì)節(jié),并在需要時(shí)將相關(guān)數(shù)據(jù)提供給Shiro。當(dāng)配置Shiro時(shí),你必須至少指定一個(gè)Realm,用于認(rèn)證和(或)授權(quán)。配置多個(gè)Realm是可以的,但是至少需要一個(gè)。
Shiro快速入門(mén)
導(dǎo)入依賴(lài)
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.7.1</version> </dependency> <!-- configure logging --> <!-- https://mvnrepository.com/artifact/org.slf4j/jcl-over-slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>2.0.0-alpha1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>2.0.0-alpha1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
配置log4j.properties
log4j.rootLogger=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n # General Apache libraries log4j.logger.org.apache=WARN # Spring log4j.logger.org.springframework=WARN # Default Shiro logging log4j.logger.org.apache.shiro=INFO # Disable verbose logging log4j.logger.org.apache.shiro.util.ThreadContext=WARN log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
配置Shiro.ini(在IDEA中需要導(dǎo)入ini插件)
[users] # user 'root' with password 'secret' and the 'admin' role root = secret, admin # user 'guest' with the password 'guest' and the 'guest' role guest = guest, guest # user 'presidentskroob' with password '12345' ("That's the same combination on # my luggage!!!" ;)), and role 'president' presidentskroob = 12345, president # user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz' darkhelmet = ludicrousspeed, darklord, schwartz # user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz' lonestarr = vespa, goodguy, schwartz # ----------------------------------------------------------------------------- # Roles with assigned permissions # # Each line conforms to the format defined in the # org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc # ----------------------------------------------------------------------------- [roles] # 'admin' role has all permissions, indicated by the wildcard '*' admin = * # The 'schwartz' role can do anything (*) with any lightsaber: schwartz = lightsaber:* # The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with # license plate 'eagle5' (instance specific id) goodguy = winnebago:drive:eagle5
快速入門(mén)實(shí)現(xiàn)類(lèi) quickStart.java
import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.DefaultSecurityManager; import org.apache.shiro.realm.text.IniRealm; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.Factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class quickStart { private static final transient Logger log = LoggerFactory.getLogger(quickStart.class); /* Shiro三大對(duì)象: Subject: 用戶(hù) SecurityManager:管理所有用戶(hù) Realm: 連接數(shù)據(jù) */ public static void main(String[] args) { // 創(chuàng)建帶有配置的Shiro SecurityManager的最簡(jiǎn)單方法 // realms, users, roles and permissions 是使用簡(jiǎn)單的INI配置。 // 我們將使用可以提取.ini文件的工廠來(lái)完成此操作, // 返回一個(gè)SecurityManager實(shí)例: // 在類(lèi)路徑的根目錄下使用shiro.ini文件 // (file:和url:前綴分別從文件和url加載): //Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); //SecurityManager securityManager = factory.getInstance(); DefaultSecurityManager securityManager = new DefaultSecurityManager(); IniRealm iniRealm = new IniRealm("classpath:shiro.ini"); securityManager.setRealm(iniRealm); // 對(duì)于這個(gè)簡(jiǎn)單的示例快速入門(mén),請(qǐng)使SecurityManager // 可作為JVM單例訪問(wèn)。大多數(shù)應(yīng)用程序都不會(huì)這樣做 // 而是依靠其容器配置或web.xml進(jìn)行 // webapps。這超出了此簡(jiǎn)單快速入門(mén)的范圍,因此 // 我們只做最低限度的工作,這樣您就可以繼續(xù)感受事物. SecurityUtils.setSecurityManager(securityManager); // 現(xiàn)在已經(jīng)建立了一個(gè)簡(jiǎn)單的Shiro環(huán)境,讓我們看看您可以做什么: // 獲取當(dāng)前用戶(hù)對(duì)象 Subject Subject currentUser = SecurityUtils.getSubject(); // 使用Session做一些事情(不需要Web或EJB容器?。?! Session session = currentUser.getSession();//通過(guò)當(dāng)前用戶(hù)拿到Session session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) { log.info("Retrieved the correct value! [" + value + "]"); } // 判斷當(dāng)前用戶(hù)是否被認(rèn)證 if (!currentUser.isAuthenticated()) { //token : 令牌,沒(méi)有獲取,隨機(jī) UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); token.setRememberMe(true); // 設(shè)置記住我 try { currentUser.login(token);//執(zhí)行登陸操作 } catch (UnknownAccountException uae) {//打印出 用戶(hù)名 log.info("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) {//打印出 密碼 log.info("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { log.info("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } // ... 在此處捕獲更多異常(也許是針對(duì)您的應(yīng)用程序的自定義異常? catch (AuthenticationException ae) { //unexpected condition? error? } } //say who they are: //print their identifying principal (in this case, a username): log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role: if (currentUser.hasRole("schwartz")) { log.info("May the Schwartz be with you!"); } else { log.info("Hello, mere mortal."); } //test a typed permission (not instance-level) if (currentUser.isPermitted("lightsaber:wield")) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: if (currentUser.isPermitted("winnebago:drive:eagle5")) { log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } //all done - log out! currentUser.logout();//注銷(xiāo) System.exit(0);//退出 } }
啟動(dòng)測(cè)試
SpringBoot-Shiro整合(最后會(huì)附上完整代碼)
前期工作
導(dǎo)入shiro-spring整合包依賴(lài)
<!-- shiro-spring整合包 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.7.1</version> </dependency>
跳轉(zhuǎn)的頁(yè)面
index.html
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>首頁(yè)</title> </head> <body> <h1>首頁(yè)</h1> <p th:text="${msg}"></p> <a th:href="@{/user/add}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >add</a>| <a th:href="@{/user/update}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >update</a> </body> </html>
add.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>add</title> </head> <body> <p>add</p> </body> </html>
update.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>update</title> </head> <body> <p>update</p> </body> </html>
編寫(xiě)shiro的配置類(lèi)ShiroConfig.java
package com.example.config; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.LinkedHashMap; import java.util.Map; @Configuration public class ShiroConfig { //3. ShiroFilterFactoryBean @Bean public ShiroFilterFactoryBean getshiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){ ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean(); //設(shè)置安全管理器 factoryBean.setSecurityManager(defaultWebSecurityManager); return factoryBean; } //2.創(chuàng)建DefaultWebSecurityManager @Bean(name = "SecurityManager") public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){ DefaultWebSecurityManager SecurityManager=new DefaultWebSecurityManager(); //3.關(guān)聯(lián)Realm SecurityManager.setRealm(userRealm); return SecurityManager; } //1.創(chuàng)建Realm對(duì)象 @Bean(name = "userRealm") public UserRealm userRealm(){ return new UserRealm(); } }
編寫(xiě)UserRealm.java
package com.example.config; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; public class UserRealm extends AuthorizingRealm { @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("授權(quán)"); return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("認(rèn)證"); return null; } }
編寫(xiě)controller測(cè)試環(huán)境是否搭建好
package com.example.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MyController { @RequestMapping({"/","/index"}) public String index(Model model){ model.addAttribute("msg","hello,shiro"); return "index"; } @RequestMapping("/user/add") public String add(){ return "user/add"; } @RequestMapping("/user/update") public String update(){ return "user/update"; } }
實(shí)現(xiàn)登錄攔截
在ShiroConfig.java文件中添加攔截
Map<String,String> filterMap = new LinkedHashMap<>(); //對(duì)/user/*下的文件只有擁有authc權(quán)限的才能訪問(wèn) filterMap.put("/user/*","authc"); //將Map存放到ShiroFilterFactoryBean中 factoryBean.setFilterChainDefinitionMap(filterMap);
這樣,代碼跑起來(lái),你點(diǎn)擊add或者update就會(huì)出現(xiàn)404錯(cuò)誤,這時(shí)候,我們?cè)倮^續(xù)添加,讓它跳轉(zhuǎn)到我們自定義的登錄頁(yè)
添加登錄攔截到登錄頁(yè)
//需進(jìn)行權(quán)限認(rèn)證時(shí)跳轉(zhuǎn)到toLogin factoryBean.setLoginUrl("/toLogin"); //權(quán)限認(rèn)證失敗時(shí)跳轉(zhuǎn)到unauthorized factoryBean.setUnauthorizedUrl("/unauthorized");
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄</title> </head> <body> <form action=""> 用戶(hù)名:<input type="text" name="username"><br> 密碼:<input type="text" name="password"><br> <input type="submit"> </form> </body> </html>
視圖跳轉(zhuǎn)添加一個(gè)login頁(yè)面跳轉(zhuǎn)
@RequestMapping("/toLogin") public String login(){ return "login"; }
上面,我們已經(jīng)成功攔截了,現(xiàn)在我們來(lái)實(shí)現(xiàn)用戶(hù)認(rèn)證
首先,我們需要一個(gè)登錄頁(yè)面
login.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>登錄</title> </head> <body> <p th:text="${msg}" style="color: red"></p> <form th:action="@{/login}"> 用戶(hù)名:<input type="text" name="username"><br> 密碼:<input type="text" name="password"><br> <input type="submit"> </form> </body> </html>
其次,去controller編寫(xiě)跳轉(zhuǎn)到登錄頁(yè)面
@RequestMapping("/login") public String login(String username,String password,Model model){ //獲得當(dāng)前的用戶(hù) Subject subject = SecurityUtils.getSubject(); //封裝用戶(hù)數(shù)據(jù) UsernamePasswordToken taken = new UsernamePasswordToken(username,password); try{//執(zhí)行登陸操作,沒(méi)有發(fā)生異常就說(shuō)明登陸成功 subject.login(taken); return "index"; }catch (UnknownAccountException e){ model.addAttribute("msg","用戶(hù)名錯(cuò)誤"); return "login"; }catch (IncorrectCredentialsException e){ model.addAttribute("msg","密碼錯(cuò)誤"); return "login"; } }
最后去UserRealm.java配置認(rèn)證
//認(rèn)證 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("認(rèn)證"); String name = "root"; String password = "123456"; UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken; if (!userToken.getUsername().equals(name)){ return null;//拋出異常 用戶(hù)名錯(cuò)誤那個(gè)異常 } //密碼認(rèn)證,shiro自己做 return new SimpleAuthenticationInfo("",password,""); }
運(yùn)行測(cè)試,成功?。?!
附上最后的完整代碼
pom.xml引入的依賴(lài)
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.4</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>springboot-08-shiro</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-08-shiro</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!-- shiro-spring整合包 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.7.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
靜態(tài)資源
index.html
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>首頁(yè)</title> </head> <body> <h1>首頁(yè)</h1> <p th:text="${msg}"></p> <a th:href="@{/user/add}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >add</a>| <a th:href="@{/user/update}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >update</a> </body> </html>
login.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>登錄</title> </head> <body> <p th:text="${msg}" style="color: red"></p> <form th:action="@{/login}"> 用戶(hù)名:<input type="text" name="username"><br> 密碼:<input type="text" name="password"><br> <input type="submit"> </form> </body> </html>
add.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>add</title> </head> <body> <p>add</p> </body> </html>
update.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>update</title> </head> <body> <p>update</p> </body> </html>
controller層
MyController.java
package com.example.controller; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MyController { @RequestMapping({"/","/index"}) public String index(Model model){ model.addAttribute("msg","hello,shiro"); return "index"; } @RequestMapping("/user/add") public String add(){ return "user/add"; } @RequestMapping("/user/update") public String update(){ return "user/update"; } @RequestMapping("/toLogin") public String toLogin(){ return "login"; } @RequestMapping("/login") public String login(String username,String password,Model model){ //獲得當(dāng)前的用戶(hù) Subject subject = SecurityUtils.getSubject(); //封裝用戶(hù)數(shù)據(jù) UsernamePasswordToken taken = new UsernamePasswordToken(username,password); try{//執(zhí)行登陸操作,沒(méi)有發(fā)生異常就說(shuō)明登陸成功 subject.login(taken); return "index"; }catch (UnknownAccountException e){ model.addAttribute("msg","用戶(hù)名錯(cuò)誤"); return "login"; }catch (IncorrectCredentialsException e){ model.addAttribute("msg","密碼錯(cuò)誤"); return "login"; } } }
config文件
ShiroConfig.java
package com.example.config; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.LinkedHashMap; import java.util.Map; @Configuration public class ShiroConfig { //4. ShiroFilterFactoryBean @Bean public ShiroFilterFactoryBean getshiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){ ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean(); //5. 設(shè)置安全管理器 factoryBean.setSecurityManager(defaultWebSecurityManager); /* shiro內(nèi)置過(guò)濾器 anon 無(wú)需授權(quán)、登錄就可以訪問(wèn),所有人可訪。 authc 需要登錄授權(quán)才能訪問(wèn)。 authcBasic Basic HTTP身份驗(yàn)證攔截器 logout 退出攔截器。退出成功后,會(huì) redirect到設(shè)置的/URI noSessionCreation 不創(chuàng)建會(huì)話連接器 perms 授權(quán)攔截器,擁有對(duì)某個(gè)資源的權(quán)限才可訪問(wèn) port 端口攔截器 rest rest風(fēng)格攔截器 roles 角色攔截器,擁有某個(gè)角色的權(quán)限才可訪問(wèn) ssl ssl攔截器。通過(guò)https協(xié)議才能通過(guò) user 用戶(hù)攔截器,需要有remember me功能方可使用 */ Map<String,String> filterMap = new LinkedHashMap<>(); //對(duì)/user/*下的文件只有擁有authc權(quán)限的才能訪問(wèn) filterMap.put("/user/*","authc"); //將Map存放到ShiroFilterFactoryBean中 factoryBean.setFilterChainDefinitionMap(filterMap); //需進(jìn)行權(quán)限認(rèn)證時(shí)跳轉(zhuǎn)到toLogin factoryBean.setLoginUrl("/toLogin"); //權(quán)限認(rèn)證失敗時(shí)跳轉(zhuǎn)到unauthorized factoryBean.setUnauthorizedUrl("/unauthorized"); return factoryBean; } //2.創(chuàng)建DefaultWebSecurityManager @Bean(name = "SecurityManager") public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){ DefaultWebSecurityManager SecurityManager=new DefaultWebSecurityManager(); //3.關(guān)聯(lián)Realm SecurityManager.setRealm(userRealm); return SecurityManager; } //1.創(chuàng)建Realm對(duì)象 @Bean(name = "userRealm") public UserRealm userRealm(){ return new UserRealm(); } }
UserRealm.java
package com.example.config; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; public class UserRealm extends AuthorizingRealm { //授權(quán) @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("授權(quán)"); return null; } //認(rèn)證 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("認(rèn)證"); String name = "root"; String password = "123456"; UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken; if (!userToken.getUsername().equals(name)){ return null;//拋出異常 用戶(hù)名錯(cuò)誤那個(gè)異常 } //密碼認(rèn)證,shiro自己做 return new SimpleAuthenticationInfo("",password,""); } }
但是,我們?cè)谟脩?hù)認(rèn)證這里,真實(shí)情況是從數(shù)據(jù)庫(kù)中取的,所以,我們接下來(lái)去實(shí)現(xiàn)一下從數(shù)據(jù)庫(kù)中取出數(shù)據(jù)來(lái)實(shí)現(xiàn)用戶(hù)認(rèn)證
Shiro整合mybatis
前期工作
在前面導(dǎo)入的依賴(lài)中,繼續(xù)添加以下依賴(lài)
<!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- 數(shù)據(jù)源Druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.5</version> </dependency> <!-- 引入mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
導(dǎo)入了mybatis和Druid,就去application.properties配置一下和Druid
Druid
spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # 自定義數(shù)據(jù)源 #Spring Boot 默認(rèn)是不注入這些屬性值的,需要自己綁定 #druid 數(shù)據(jù)源專(zhuān)有配置 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true #配置監(jiān)控統(tǒng)計(jì)攔截的filters,stat:監(jiān)控統(tǒng)計(jì)、log4j:日志記錄、wall:防御sql注入 #如果允許時(shí)報(bào)錯(cuò) java.lang.ClassNotFoundException: org.apache.log4j.Priority #則導(dǎo)入 log4j 依賴(lài)即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis
mybatis: type-aliases-package: com.example.pojo mapper-locations: classpath:mapper/*.xml
連接數(shù)據(jù)庫(kù)
編寫(xiě)實(shí)體類(lèi)
package com.example.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private Integer id; private String name; private String pwd; }
編寫(xiě)mapper
package com.example.mapper; import com.example.pojo.User; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; @Repository @Mapper public interface UserMapper { public User getUserByName(String name); }
編寫(xiě)mapper.xml
<?xml version="1.0" encoding="UTF8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.mapper.UserMapper"> <select id="getUserByName" parameterType="String" resultType="User"> select * from mybatis.user where name=#{name} </select> </mapper>
編寫(xiě)service
package com.example.service; import com.example.pojo.User; public interface UserService { public User getUserByName(String name); }
package com.example.service; import com.example.mapper.UserMapper; import com.example.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService{ @Autowired UserMapper userMapper; @Override public User getUserByName(String name) { return userMapper.getUserByName(name); } }
使用數(shù)據(jù)庫(kù)中的數(shù)據(jù)
修改UserRealm.java即可
package com.example.config; import com.example.pojo.User; import com.example.service.UserService; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; public class UserRealm extends AuthorizingRealm { @Autowired UserService userService; //授權(quán) @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("授權(quán)"); return null; } //認(rèn)證 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("認(rèn)證"); UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken; //連接真實(shí)的數(shù)據(jù)庫(kù) User user = userService.getUserByName(userToken.getUsername()); if (user==null){ return null;//拋出異常 用戶(hù)名錯(cuò)誤那個(gè)異常 } //密碼認(rèn)證,shiro自己做 return new SimpleAuthenticationInfo("",user.getPwd(),""); } }
認(rèn)證搞完了,我們?cè)賮?lái)看看授權(quán)
在ShiroConfig.java文件加入授權(quán),加入這行代碼: filterMap.put("/user/add","perms[user:add]");//只有擁有user:add權(quán)限的人才能訪問(wèn)add,注意授權(quán)的位置在認(rèn)證前面,不然授權(quán)會(huì)認(rèn)證不了;
運(yùn)行測(cè)試:add頁(yè)面無(wú)法訪問(wèn)
授權(quán)同理:filterMap.put("/user/update","perms[user:update]");//只有擁有user:update權(quán)限的人才能訪問(wèn)update
自定義一個(gè)未授權(quán)跳轉(zhuǎn)頁(yè)面
在ShiroConfig.java文件設(shè)置未授權(quán)時(shí)跳轉(zhuǎn)到unauthorized頁(yè)面,加入這行代碼:
factoryBean.setUnauthorizedUrl("/unauthorized"); 2. 去Mycontroller寫(xiě)跳轉(zhuǎn)未授權(quán)頁(yè)面
@RequestMapping("/unauthorized") @ResponseBody//懶得寫(xiě)界面,返回一個(gè)字符串 public String unauthorized(){ return "沒(méi)有授權(quán),無(wú)法訪問(wèn)"; }
運(yùn)行效果:
從數(shù)據(jù)庫(kù)中接受用戶(hù)的權(quán)限,進(jìn)行判斷
在數(shù)據(jù)庫(kù)中添加一個(gè)屬性perms,相應(yīng)的實(shí)體類(lèi)也要修改
修改UserRealm.java
package com.example.config; import com.example.pojo.User; import com.example.service.UserService; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; public class UserRealm extends AuthorizingRealm { @Autowired UserService userService; //授權(quán) @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("授權(quán)"); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //沒(méi)有使用數(shù)據(jù)庫(kù),直接自己設(shè)置的用戶(hù)權(quán)限,給每個(gè)人都設(shè)置了,現(xiàn)實(shí)中要從數(shù)據(jù)庫(kù)中取 //info.addStringPermission("user:add"); //從數(shù)據(jù)庫(kù)中得到權(quán)限信息 //獲得當(dāng)前登錄的對(duì)象 Subject subject = SecurityUtils.getSubject(); //拿到User對(duì)象,通過(guò)getPrincipal()獲得 User currentUser = (User) subject.getPrincipal(); //設(shè)置當(dāng)前用戶(hù)的權(quán)限 info.addStringPermission(currentUser.getPerms()); return info; } //認(rèn)證 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("認(rèn)證"); UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken; //連接真實(shí)的數(shù)據(jù)庫(kù) User user = userService.getUserByName(userToken.getUsername()); if (user==null){ return null;//拋出異常 用戶(hù)名錯(cuò)誤那個(gè)異常 } //密碼認(rèn)證,shiro自己做 return new SimpleAuthenticationInfo(user,user.getPwd(),""); } }
有了授權(quán)后,就又出現(xiàn)了一個(gè)問(wèn)題,我們是不是要讓用戶(hù)沒(méi)有權(quán)限的東西,就看不見(jiàn)呢?這時(shí)候,就出現(xiàn)了Shiro-thymeleaf整合
Shiro-thymeleaf整合
導(dǎo)入整合的依賴(lài)
<!-- 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>
在ShiroConfig整合ShiroDialect
//整合ShiroDialect: 用來(lái)整合 shiro thymeleaf @Bean public ShiroDialect getShiroDialect(){ return new ShiroDialect(); }
修改index頁(yè)面
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"> <!-- 三個(gè)命名空間 xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security" xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro" --> <head> <meta charset="UTF-8"> <title>首頁(yè)</title> </head> <body> <h1>首頁(yè)</h1> <p th:text="${msg}"></p> <!--判斷是否有用戶(hù)登錄,如果有就不顯示登錄按鈕--> <div th:if="${session.loginUser==null}"> <a th:href="@{/toLogin}" rel="external nofollow" >登錄</a> </div> <div shiro:hasPermission="user:add"> <a th:href="@{/user/add}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >add</a> </div> <div shiro:hasPermission="user:update"> <a th:href="@{/user/update}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >update</a> </div> </body> </html>
判斷是否有用戶(hù)登錄
//這個(gè)是整合shiro和thymeleaf用到的,讓登錄按鈕消失的判斷 Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(); session.setAttribute("loginUser", user);
測(cè)試
以上就是Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)的詳細(xì)內(nèi)容,更多關(guān)于Java安全框架——Shiro的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java數(shù)據(jù)結(jié)構(gòu)之二叉排序樹(shù)的實(shí)現(xiàn)
二叉排序樹(shù)(Binary Sort Tree),又稱(chēng)二叉查找樹(shù)(Binary Search Tree),亦稱(chēng)二叉搜索樹(shù)。本文詳細(xì)介紹了二叉排序樹(shù)的原理,并且提供了Java代碼的完全實(shí)現(xiàn)。需要的可以參考一下2022-01-01Java使用設(shè)計(jì)模式中的代理模式構(gòu)建項(xiàng)目的實(shí)例展示
這篇文章主要介紹了Java使用設(shè)計(jì)模式中的代理模式構(gòu)建項(xiàng)目的實(shí)例展示,代理模式中的代理對(duì)象可以在客戶(hù)端和目標(biāo)對(duì)象之間起到中介的作用,需要的朋友可以參考下2016-05-05Spring boot自定義http反饋狀態(tài)碼詳解
這篇文章主要給大家介紹了Spring boot自定義http反饋狀態(tài)碼的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編一起來(lái)學(xué)習(xí)學(xué)習(xí)吧。2017-06-06詳談鎖和監(jiān)視器之間的區(qū)別_Java并發(fā)
下面小編就為大家?guī)?lái)一篇詳談鎖和監(jiān)視器之間的區(qū)別_Java并發(fā)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-06-06基于java SSM springboot實(shí)現(xiàn)抗疫物質(zhì)信息管理系統(tǒng)
這篇文章主要介紹了基于JAVA SSM springboot實(shí)現(xiàn)的抗疫物質(zhì)信息管理系統(tǒng),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-08-08詳解Java并發(fā)編程之volatile關(guān)鍵字
這篇文章主要為大家介紹了Java并發(fā)編程之volatile關(guān)鍵字,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2021-11-11