Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)
導(dǎo)入依賴
<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中需要導(dǎo)入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
快速入門實(shí)現(xiàn)類 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: 連接數(shù)據(jù) */ public static void main(String[] args) {// 創(chuàng)建帶有配置的Shiro SecurityManager的最簡單方法// realms, users, roles and permissions 是使用簡單的INI配置。// 我們將使用可以提取.ini文件的工廠來完成此操作,// 返回一個(gè)SecurityManager實(shí)例:// 在類路徑的根目錄下使用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);// 對于這個(gè)簡單的示例快速入門,請使SecurityManager// 可作為JVM單例訪問。大多數(shù)應(yīng)用程序都不會(huì)這樣做// 而是依靠其容器配置或web.xml進(jìn)行// webapps。這超出了此簡單快速入門的范圍,因此// 我們只做最低限度的工作,這樣您就可以繼續(xù)感受事物.SecurityUtils.setSecurityManager(securityManager);// 現(xiàn)在已經(jīng)建立了一個(gè)簡單的Shiro環(huán)境,讓我們看看您可以做什么:// 獲取當(dāng)前用戶對象 SubjectSubject currentUser = SecurityUtils.getSubject();// 使用Session做一些事情(不需要Web或EJB容器!!!Session session = currentUser.getSession();//通過當(dāng)前用戶拿到Sessionsession.setAttribute('someKey', 'aValue');String value = (String) session.getAttribute('someKey');if (value.equals('aValue')) { log.info('Retrieved the correct value! [' + value + ']');}// 判斷當(dāng)前用戶是否被認(rèn)證if (!currentUser.isAuthenticated()) { //token : 令牌,沒有獲取,隨機(jī) UsernamePasswordToken token = new UsernamePasswordToken('lonestarr', 'vespa'); token.setRememberMe(true); // 設(shè)置記住我 try {currentUser.login(token);//執(zhí)行登陸操作 } 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.'); } // ... 在此處捕獲更多異常(也許是針對您的應(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();//注銷System.exit(0);//退出 }}
啟動(dòng)測試
前期工作
導(dǎo)入shiro-spring整合包依賴
<!-- shiro-spring整合包 --><dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.7.1</version></dependency>
跳轉(zhuǎn)的頁面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://m.cgvv.com.cn/bcjs/@{/user/add}' rel='external nofollow' rel='external nofollow' rel='external nofollow' >add</a>| <a th:href='http://m.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();//設(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)RealmSecurityManager.setRealm(userRealm);return SecurityManager; } //1.創(chuàng)建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('授權(quán)');return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println('認(rèn)證');return null; }}
編寫controller測試環(huán)境是否搭建好
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'; }}
實(shí)現(xiàn)登錄攔截
在ShiroConfig.java文件中添加攔截
Map<String,String> filterMap = new LinkedHashMap<>();//對/user/*下的文件只有擁有authc權(quán)限的才能訪問filterMap.put('/user/*','authc');//將Map存放到ShiroFilterFactoryBean中factoryBean.setFilterChainDefinitionMap(filterMap);
這樣,代碼跑起來,你點(diǎn)擊add或者update就會(huì)出現(xiàn)404錯(cuò)誤,這時(shí)候,我們再繼續(xù)添加,讓它跳轉(zhuǎn)到我們自定義的登錄頁
添加登錄攔截到登錄頁
//需進(jìn)行權(quán)限認(rèn)證時(shí)跳轉(zhuǎn)到toLoginfactoryBean.setLoginUrl('/toLogin');//權(quán)限認(rèn)證失敗時(shí)跳轉(zhuǎn)到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>
視圖跳轉(zhuǎn)添加一個(gè)login頁面跳轉(zhuǎn)
@RequestMapping('/toLogin') public String login(){return 'login'; }
上面,我們已經(jīng)成功攔截了,現(xiàn)在我們來實(shí)現(xiàn)用戶認(rèn)證
首先,我們需要一個(gè)登錄頁面
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編寫跳轉(zhuǎn)到登錄頁面
@RequestMapping('/login') public String login(String username,String password,Model model){//獲得當(dāng)前的用戶Subject subject = SecurityUtils.getSubject();//封裝用戶數(shù)據(jù)UsernamePasswordToken taken = new UsernamePasswordToken(username,password);try{//執(zhí)行登陸操作,沒有發(fā)生異常就說明登陸成功 subject.login(taken); return 'index';}catch (UnknownAccountException e){ model.addAttribute('msg','用戶名錯(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;//拋出異常 用戶名錯(cuò)誤那個(gè)異常}//密碼認(rèn)證,shiro自己做return new SimpleAuthenticationInfo('',password,''); }
運(yùn)行測試,成功!!!
附上最后的完整代碼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>
靜態(tài)資源
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://m.cgvv.com.cn/bcjs/@{/user/add}' rel='external nofollow' rel='external nofollow' rel='external nofollow' >add</a>| <a th:href='http://m.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){//獲得當(dāng)前的用戶Subject subject = SecurityUtils.getSubject();//封裝用戶數(shù)據(jù)UsernamePasswordToken taken = new UsernamePasswordToken(username,password);try{//執(zhí)行登陸操作,沒有發(fā)生異常就說明登陸成功 subject.login(taken); return 'index';}catch (UnknownAccountException e){ model.addAttribute('msg','用戶名錯(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;@Configurationpublic class ShiroConfig { //4. ShiroFilterFactoryBean @Bean public ShiroFilterFactoryBean getshiroFilterFactoryBean(@Qualifier('SecurityManager') DefaultWebSecurityManager defaultWebSecurityManager){ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();//5. 設(shè)置安全管理器factoryBean.setSecurityManager(defaultWebSecurityManager);/* shiro內(nèi)置過濾器 anon無需授權(quán)、登錄就可以訪問,所有人可訪。 authc 需要登錄授權(quán)才能訪問。 authcBasicBasic HTTP身份驗(yàn)證攔截器 logout退出攔截器。退出成功后,會(huì) redirect到設(shè)置的/URI noSessionCreation不創(chuàng)建會(huì)話連接器 perms授權(quán)攔截器,擁有對某個(gè)資源的權(quán)限才可訪問 port端口攔截器 restrest風(fēng)格攔截器 roles角色攔截器,擁有某個(gè)角色的權(quán)限才可訪問 sslssl攔截器。通過https協(xié)議才能通過 user用戶攔截器,需要有remember me功能方可使用 */Map<String,String> filterMap = new LinkedHashMap<>();//對/user/*下的文件只有擁有authc權(quán)限的才能訪問filterMap.put('/user/*','authc');//將Map存放到ShiroFilterFactoryBean中factoryBean.setFilterChainDefinitionMap(filterMap);//需進(jìn)行權(quán)限認(rèn)證時(shí)跳轉(zhuǎn)到toLoginfactoryBean.setLoginUrl('/toLogin');//權(quán)限認(rèn)證失敗時(shí)跳轉(zhuǎn)到unauthorizedfactoryBean.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)RealmSecurityManager.setRealm(userRealm);return SecurityManager; } //1.創(chuàng)建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 { //授權(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;//拋出異常 用戶名錯(cuò)誤那個(gè)異常}//密碼認(rèn)證,shiro自己做return new SimpleAuthenticationInfo('',password,''); }}
但是,我們在用戶認(rèn)證這里,真實(shí)情況是從數(shù)據(jù)庫中取的,所以,我們接下來去實(shí)現(xiàn)一下從數(shù)據(jù)庫中取出數(shù)據(jù)來實(shí)現(xiàn)用戶認(rèn)證
Shiro整合mybatis前期工作
在前面導(dǎo)入的依賴中,繼續(xù)添加以下依賴
<!-- 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配置一下和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 # 自定義數(shù)據(jù)源 #Spring Boot 默認(rèn)是不注入這些屬性值的,需要自己綁定 #druid 數(shù)據(jù)源專有配置 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 依賴即可,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ù)庫編寫實(shí)體類
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); }}
使用數(shù)據(jù)庫中的數(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ù)庫User user = userService.getUserByName(userToken.getUsername());if (user==null){ return null;//拋出異常 用戶名錯(cuò)誤那個(gè)異常}//密碼認(rèn)證,shiro自己做return new SimpleAuthenticationInfo('',user.getPwd(),''); }}認(rèn)證搞完了,我們再來看看授權(quán)
在ShiroConfig.java文件加入授權(quán),加入這行代碼: filterMap.put('/user/add','perms[user:add]');//只有擁有user:add權(quán)限的人才能訪問add,注意授權(quán)的位置在認(rèn)證前面,不然授權(quán)會(huì)認(rèn)證不了;
運(yùn)行測試:add頁面無法訪問
授權(quán)同理:filterMap.put('/user/update','perms[user:update]');//只有擁有user:update權(quán)限的人才能訪問update
自定義一個(gè)未授權(quán)跳轉(zhuǎn)頁面
在ShiroConfig.java文件設(shè)置未授權(quán)時(shí)跳轉(zhuǎn)到unauthorized頁面,加入這行代碼:factoryBean.setUnauthorizedUrl('/unauthorized'); 2. 去Mycontroller寫跳轉(zhuǎn)未授權(quán)頁面
@RequestMapping('/unauthorized') @ResponseBody//懶得寫界面,返回一個(gè)字符串 public String unauthorized(){return '沒有授權(quán),無法訪問'; }
運(yùn)行效果:
從數(shù)據(jù)庫中接受用戶的權(quán)限,進(jìn)行判斷
在數(shù)據(jù)庫中添加一個(gè)屬性perms,相應(yīng)的實(shí)體類也要修改
修改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();//沒有使用數(shù)據(jù)庫,直接自己設(shè)置的用戶權(quán)限,給每個(gè)人都設(shè)置了,現(xiàn)實(shí)中要從數(shù)據(jù)庫中取//info.addStringPermission('user:add');//從數(shù)據(jù)庫中得到權(quán)限信息//獲得當(dāng)前登錄的對象Subject subject = SecurityUtils.getSubject();//拿到User對象,通過getPrincipal()獲得User currentUser = (User) subject.getPrincipal();//設(shè)置當(dāng)前用戶的權(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ù)庫User user = userService.getUserByName(userToken.getUsername());if (user==null){ return null;//拋出異常 用戶名錯(cuò)誤那個(gè)異常}//密碼認(rèn)證,shiro自己做return new SimpleAuthenticationInfo(user,user.getPwd(),''); }}
有了授權(quán)后,就又出現(xiàn)了一個(gè)問題,我們是不是要讓用戶沒有權(quán)限的東西,就看不見呢?這時(shí)候,就出現(xiàn)了Shiro-thymeleaf整合
Shiro-thymeleaf整合導(dǎo)入整合的依賴
<!-- 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'><!-- 三個(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>首頁</title></head><body><h1>首頁</h1><p th:text='${msg}'></p><!--判斷是否有用戶登錄,如果有就不顯示登錄按鈕--><div th:if='${session.loginUser==null}'> <a th:href='http://m.cgvv.com.cn/bcjs/@{/toLogin}' rel='external nofollow' >登錄</a></div><div shiro:hasPermission='user:add'> <a th:href='http://m.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://m.cgvv.com.cn/bcjs/@{/user/update}' rel='external nofollow' rel='external nofollow' rel='external nofollow' >update</a></div></body></html>
判斷是否有用戶登錄
//這個(gè)是整合shiro和thymeleaf用到的,讓登錄按鈕消失的判斷Subject subject = SecurityUtils.getSubject();Session session = subject.getSession();session.setAttribute('loginUser', user);
測試
以上就是Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)的詳細(xì)內(nèi)容,更多關(guān)于Java安全框架——Shiro的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. .NET SkiaSharp 生成二維碼驗(yàn)證碼及指定區(qū)域截取方法實(shí)現(xiàn)2. css代碼優(yōu)化的12個(gè)技巧3. HTTP協(xié)議常用的請求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))4. idea設(shè)置提示不區(qū)分大小寫的方法5. CentOS郵件服務(wù)器搭建系列—— POP / IMAP 服務(wù)器的構(gòu)建( Dovecot )6. ASP.NET MVC通過勾選checkbox更改select的內(nèi)容7. Django使用HTTP協(xié)議向服務(wù)器傳參方式小結(jié)8. IntelliJ IDEA創(chuàng)建web項(xiàng)目的方法9. django創(chuàng)建css文件夾的具體方法10. 原生JS實(shí)現(xiàn)記憶翻牌游戲
