Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)
導入依賴
<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, stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n# General Apache librarieslog4j.logger.org.apache=WARN# Springlog4j.logger.org.springframework=WARN# Default Shiro logginglog4j.logger.org.apache.shiro=INFO# Disable verbose logginglog4j.logger.org.apache.shiro.util.ThreadContext=WARNlog4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
配置Shiro.ini(在IDEA中需要導入ini插件)
[users]# user ’root’ with password ’secret’ and the ’admin’ roleroot = secret, admin# user ’guest’ with the password ’guest’ and the ’guest’ roleguest = 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
快速入門實現類 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三大對象:Subject: 用戶SecurityManager:管理所有用戶Realm: 連接數據 */ public static void main(String[] args) {// 創建帶有配置的Shiro SecurityManager的最簡單方法// realms, users, roles and permissions 是使用簡單的INI配置。// 我們將使用可以提取.ini文件的工廠來完成此操作,// 返回一個SecurityManager實例:// 在類路徑的根目錄下使用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);// 對于這個簡單的示例快速入門,請使SecurityManager// 可作為JVM單例訪問。大多數應用程序都不會這樣做// 而是依靠其容器配置或web.xml進行// webapps。這超出了此簡單快速入門的范圍,因此// 我們只做最低限度的工作,這樣您就可以繼續感受事物.SecurityUtils.setSecurityManager(securityManager);// 現在已經建立了一個簡單的Shiro環境,讓我們看看您可以做什么:// 獲取當前用戶對象 SubjectSubject currentUser = SecurityUtils.getSubject();// 使用Session做一些事情(不需要Web或EJB容器!!!Session session = currentUser.getSession();//通過當前用戶拿到Sessionsession.setAttribute('someKey', 'aValue');String value = (String) session.getAttribute('someKey');if (value.equals('aValue')) { log.info('Retrieved the correct value! [' + value + ']');}// 判斷當前用戶是否被認證if (!currentUser.isAuthenticated()) { //token : 令牌,沒有獲取,隨機 UsernamePasswordToken token = new UsernamePasswordToken('lonestarr', 'vespa'); token.setRememberMe(true); // 設置記住我 try {currentUser.login(token);//執行登陸操作 } catch (UnknownAccountException uae) {//打印出 用戶名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.'); } // ... 在此處捕獲更多異常(也許是針對您的應用程序的自定義異常? 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();//注銷System.exit(0);//退出 }}
啟動測試
前期工作
導入shiro-spring整合包依賴
<!-- shiro-spring整合包 --><dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.7.1</version></dependency>
跳轉的頁面index.html
<html lang='en' xmlns:th='http://www.w3.org/1999/xhtml'><head> <meta charset='UTF-8'> <title>首頁</title></head><body><h1>首頁</h1><p th:text='${msg}'></p><a th:href='http://www.cgvv.com.cn/bcjs/@{/user/add}' rel='external nofollow' rel='external nofollow' rel='external nofollow' >add</a>| <a th:href='http://www.cgvv.com.cn/bcjs/@{/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>
編寫shiro的配置類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;@Configurationpublic class ShiroConfig { //3. ShiroFilterFactoryBean @Bean public ShiroFilterFactoryBean getshiroFilterFactoryBean(@Qualifier('SecurityManager') DefaultWebSecurityManager defaultWebSecurityManager){ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();//設置安全管理器factoryBean.setSecurityManager(defaultWebSecurityManager);return factoryBean; } //2.創建DefaultWebSecurityManager @Bean(name = 'SecurityManager') public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier('userRealm') UserRealm userRealm){DefaultWebSecurityManager SecurityManager=new DefaultWebSecurityManager();//3.關聯RealmSecurityManager.setRealm(userRealm);return SecurityManager; } //1.創建Realm對象 @Bean(name = 'userRealm') public UserRealm userRealm(){return new UserRealm(); }}
編寫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('授權');return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println('認證');return null; }}
編寫controller測試環境是否搭建好
package com.example.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic 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'; }}
實現登錄攔截
在ShiroConfig.java文件中添加攔截
Map<String,String> filterMap = new LinkedHashMap<>();//對/user/*下的文件只有擁有authc權限的才能訪問filterMap.put('/user/*','authc');//將Map存放到ShiroFilterFactoryBean中factoryBean.setFilterChainDefinitionMap(filterMap);
這樣,代碼跑起來,你點擊add或者update就會出現404錯誤,這時候,我們再繼續添加,讓它跳轉到我們自定義的登錄頁
添加登錄攔截到登錄頁
//需進行權限認證時跳轉到toLoginfactoryBean.setLoginUrl('/toLogin');//權限認證失敗時跳轉到unauthorizedfactoryBean.setUnauthorizedUrl('/unauthorized');
login.html
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>登錄</title></head><body><form action=''> 用戶名:<input type='text' name='username'><br> 密碼:<input type='text' name='password'><br> <input type='submit'></form></body></html>
視圖跳轉添加一個login頁面跳轉
@RequestMapping('/toLogin') public String login(){return 'login'; }
上面,我們已經成功攔截了,現在我們來實現用戶認證
首先,我們需要一個登錄頁面
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}'> 用戶名:<input type='text' name='username'><br> 密碼:<input type='text' name='password'><br> <input type='submit'></form></body></html>
其次,去controller編寫跳轉到登錄頁面
@RequestMapping('/login') public String login(String username,String password,Model model){//獲得當前的用戶Subject subject = SecurityUtils.getSubject();//封裝用戶數據UsernamePasswordToken taken = new UsernamePasswordToken(username,password);try{//執行登陸操作,沒有發生異常就說明登陸成功 subject.login(taken); return 'index';}catch (UnknownAccountException e){ model.addAttribute('msg','用戶名錯誤'); return 'login';}catch (IncorrectCredentialsException e){ model.addAttribute('msg','密碼錯誤'); return 'login';} }
最后去UserRealm.java配置認證
//認證 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println('認證');String name = 'root';String password = '123456';UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;if (!userToken.getUsername().equals(name)){ return null;//拋出異常 用戶名錯誤那個異常}//密碼認證,shiro自己做return new SimpleAuthenticationInfo('',password,''); }
運行測試,成功!!!
附上最后的完整代碼pom.xml引入的依賴
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>
靜態資源
index.html
<html lang='en' xmlns:th='http://www.w3.org/1999/xhtml'><head> <meta charset='UTF-8'> <title>首頁</title></head><body><h1>首頁</h1><p th:text='${msg}'></p><a th:href='http://www.cgvv.com.cn/bcjs/@{/user/add}' rel='external nofollow' rel='external nofollow' rel='external nofollow' >add</a>| <a th:href='http://www.cgvv.com.cn/bcjs/@{/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}'> 用戶名:<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;@Controllerpublic 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){//獲得當前的用戶Subject subject = SecurityUtils.getSubject();//封裝用戶數據UsernamePasswordToken taken = new UsernamePasswordToken(username,password);try{//執行登陸操作,沒有發生異常就說明登陸成功 subject.login(taken); return 'index';}catch (UnknownAccountException e){ model.addAttribute('msg','用戶名錯誤'); return 'login';}catch (IncorrectCredentialsException e){ model.addAttribute('msg','密碼錯誤'); 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;@Configurationpublic class ShiroConfig { //4. ShiroFilterFactoryBean @Bean public ShiroFilterFactoryBean getshiroFilterFactoryBean(@Qualifier('SecurityManager') DefaultWebSecurityManager defaultWebSecurityManager){ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();//5. 設置安全管理器factoryBean.setSecurityManager(defaultWebSecurityManager);/* shiro內置過濾器 anon無需授權、登錄就可以訪問,所有人可訪。 authc 需要登錄授權才能訪問。 authcBasicBasic HTTP身份驗證攔截器 logout退出攔截器。退出成功后,會 redirect到設置的/URI noSessionCreation不創建會話連接器 perms授權攔截器,擁有對某個資源的權限才可訪問 port端口攔截器 restrest風格攔截器 roles角色攔截器,擁有某個角色的權限才可訪問 sslssl攔截器。通過https協議才能通過 user用戶攔截器,需要有remember me功能方可使用 */Map<String,String> filterMap = new LinkedHashMap<>();//對/user/*下的文件只有擁有authc權限的才能訪問filterMap.put('/user/*','authc');//將Map存放到ShiroFilterFactoryBean中factoryBean.setFilterChainDefinitionMap(filterMap);//需進行權限認證時跳轉到toLoginfactoryBean.setLoginUrl('/toLogin');//權限認證失敗時跳轉到unauthorizedfactoryBean.setUnauthorizedUrl('/unauthorized');return factoryBean; } //2.創建DefaultWebSecurityManager @Bean(name = 'SecurityManager') public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier('userRealm') UserRealm userRealm){DefaultWebSecurityManager SecurityManager=new DefaultWebSecurityManager();//3.關聯RealmSecurityManager.setRealm(userRealm);return SecurityManager; } //1.創建Realm對象 @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 { //授權 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println('授權');return null; } //認證 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println('認證');String name = 'root';String password = '123456';UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;if (!userToken.getUsername().equals(name)){ return null;//拋出異常 用戶名錯誤那個異常}//密碼認證,shiro自己做return new SimpleAuthenticationInfo('',password,''); }}
但是,我們在用戶認證這里,真實情況是從數據庫中取的,所以,我們接下來去實現一下從數據庫中取出數據來實現用戶認證
Shiro整合mybatis前期工作
在前面導入的依賴中,繼續添加以下依賴
<!-- 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><!-- 數據源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>
導入了mybatis和Druid,就去application.properties配置一下和DruidDruid
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 # 自定義數據源 #Spring Boot 默認是不注入這些屬性值的,需要自己綁定 #druid 數據源專有配置 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 #配置監控統計攔截的filters,stat:監控統計、log4j:日志記錄、wall:防御sql注入 #如果允許時報錯 java.lang.ClassNotFoundException: org.apache.log4j.Priority #則導入 log4j 依賴即可,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
連接數據庫編寫實體類
package com.example.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data@AllArgsConstructor@NoArgsConstructorpublic class User {private Integer id;private String name;private String pwd;}
編寫mapper
package com.example.mapper;import com.example.pojo.User;import org.apache.ibatis.annotations.Mapper;import org.springframework.stereotype.Repository;@Repository@Mapperpublic interface UserMapper { public User getUserByName(String name);}
編寫mapper.xml
<?xml version='1.0' encoding='UTF8' ?><!DOCTYPE mapperPUBLIC '-//mybatis.org//DTD Mapper 3.0//EN''http://mybatis.org/dtd/mybatis-3-mapper.dtd'><mapper namespace='com.example.mapper.UserMapper'> <select parameterType='String' resultType='User'>select * from mybatis.user where name=#{name} </select></mapper>
編寫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;@Servicepublic class UserServiceImpl implements UserService{ @Autowired UserMapper userMapper; @Override public User getUserByName(String name) {return userMapper.getUserByName(name); }}
使用數據庫中的數據
修改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; //授權 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println('授權');return null; } //認證 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println('認證');UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;//連接真實的數據庫User user = userService.getUserByName(userToken.getUsername());if (user==null){ return null;//拋出異常 用戶名錯誤那個異常}//密碼認證,shiro自己做return new SimpleAuthenticationInfo('',user.getPwd(),''); }}認證搞完了,我們再來看看授權
在ShiroConfig.java文件加入授權,加入這行代碼: filterMap.put('/user/add','perms[user:add]');//只有擁有user:add權限的人才能訪問add,注意授權的位置在認證前面,不然授權會認證不了;
運行測試:add頁面無法訪問
授權同理:filterMap.put('/user/update','perms[user:update]');//只有擁有user:update權限的人才能訪問update
自定義一個未授權跳轉頁面
在ShiroConfig.java文件設置未授權時跳轉到unauthorized頁面,加入這行代碼:factoryBean.setUnauthorizedUrl('/unauthorized'); 2. 去Mycontroller寫跳轉未授權頁面
@RequestMapping('/unauthorized') @ResponseBody//懶得寫界面,返回一個字符串 public String unauthorized(){return '沒有授權,無法訪問'; }
運行效果:
從數據庫中接受用戶的權限,進行判斷
在數據庫中添加一個屬性perms,相應的實體類也要修改
修改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; //授權 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println('授權');SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();//沒有使用數據庫,直接自己設置的用戶權限,給每個人都設置了,現實中要從數據庫中取//info.addStringPermission('user:add');//從數據庫中得到權限信息//獲得當前登錄的對象Subject subject = SecurityUtils.getSubject();//拿到User對象,通過getPrincipal()獲得User currentUser = (User) subject.getPrincipal();//設置當前用戶的權限info.addStringPermission(currentUser.getPerms());return info; } //認證 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println('認證');UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;//連接真實的數據庫User user = userService.getUserByName(userToken.getUsername());if (user==null){ return null;//拋出異常 用戶名錯誤那個異常}//密碼認證,shiro自己做return new SimpleAuthenticationInfo(user,user.getPwd(),''); }}
有了授權后,就又出現了一個問題,我們是不是要讓用戶沒有權限的東西,就看不見呢?這時候,就出現了Shiro-thymeleaf整合
Shiro-thymeleaf整合導入整合的依賴
<!-- 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: 用來整合 shiro thymeleaf @Bean public ShiroDialect getShiroDialect(){return new ShiroDialect(); }
修改index頁面
<html lang='en' xmlns:th='http://www.thymeleaf.org' xmlns:shiro='http://www.thymeleaf.org/thymeleaf-extras-shiro'><!-- 三個命名空間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>首頁</title></head><body><h1>首頁</h1><p th:text='${msg}'></p><!--判斷是否有用戶登錄,如果有就不顯示登錄按鈕--><div th:if='${session.loginUser==null}'> <a th:href='http://www.cgvv.com.cn/bcjs/@{/toLogin}' rel='external nofollow' >登錄</a></div><div shiro:hasPermission='user:add'> <a th:href='http://www.cgvv.com.cn/bcjs/@{/user/add}' rel='external nofollow' rel='external nofollow' rel='external nofollow' >add</a></div><div shiro:hasPermission='user:update'> <a th:href='http://www.cgvv.com.cn/bcjs/@{/user/update}' rel='external nofollow' rel='external nofollow' rel='external nofollow' >update</a></div></body></html>
判斷是否有用戶登錄
//這個是整合shiro和thymeleaf用到的,讓登錄按鈕消失的判斷Subject subject = SecurityUtils.getSubject();Session session = subject.getSession();session.setAttribute('loginUser', user);
測試
以上就是Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)的詳細內容,更多關于Java安全框架——Shiro的資料請關注好吧啦網其它相關文章!
相關文章: