日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot整合Shiro实现登录认证和授权CHCache

發(fā)布時間:2023/12/3 javascript 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot整合Shiro实现登录认证和授权CHCache 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

    • 一、 springboot實現(xiàn)普通登錄
      • 1 添加依賴
      • 2 編寫配置文件
      • 3 新建實體類和mapper
      • 4 編寫業(yè)務(wù)層代碼
      • 5 編寫控制器
      • 6 編寫啟動類
      • 7 編寫登錄頁面和主頁面
    • 二、 springboot整合shiro實現(xiàn)登錄認(rèn)證和憑證匹配
      • 1 添加依賴
      • 2 自定義Realm
      • 3 編寫配置
      • 4 userService新增單元方法:使用shiro認(rèn)證
      • 5 憑證匹配器
        • 5.1 修改ShiroConfig
        • 5.2 修改MyRealm
    • 三、 remember me實現(xiàn)---shiro已經(jīng)集成
      • 1 修改application.yml-----增加shiro的loginUrl地址
      • 2 增加記住我的按鈕
      • 3 修改Controller
      • 4 修改ShiroConfig
    • 四、 配置退出
      • 1 修改配置類
      • 2 修改主頁面
    • 五、 授權(quán)
      • 1 簡介
      • 2 Thymeleaf整合shiro
        • 2.1 添加依賴
        • 2.2 修改配置類(負(fù)責(zé)解析thymeleaf中shiro的相關(guān)屬性)
        • 2.3 修改Realm
        • 2.4 修改main.html
      • 3 使用注解判斷方法是否具有權(quán)限執(zhí)行
        • 3.1 修改main.html
        • 3.2 修改UserController類
        • 3.3 新建依賴處理類
    • 六 EHCache
      • 1 ehcache簡介
      • 2 EHCache API演示
        • 2.1 添加依賴
        • 2.2 新建配置文件
    • 七 Shiro和EhCache整合
      • 1 添加依賴
      • 2 編寫ehcache緩存配置
      • 3 修改配置文件
    • 八 Shiro中Session對象獲取

一、 springboot實現(xiàn)普通登錄

1 添加依賴

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 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.bjsxt</groupId><artifactId>02_shiro_springboot_login</artifactId><version>1.0-SNAPSHOT</version><!--配置繼承--><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.10.RELEASE</version></parent><!--配置依賴--><dependencies><!--配置web啟動器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--配置mybatis啟動器--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.1</version></dependency><!--配置mysql驅(qū)動--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.48</version></dependency><!--配置Thrmeleaf啟動器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency></project>

2 編寫配置文件

新建application.yml

spring:datasource:driver-class-name: com.mysql.jdbc.Driverusername: rooturl: jdbc:mysql://localhost:3306/springboot-loginpassword: 1234 ##配置mapper的xml文件的路徑 mybatis:mapper-locations: classpath:mybatis/*.xml

3 新建實體類和mapper

新建com.bjsxt.pojo.User

public class User {private Long id;private String username;private String pwd;// 省略getter和setter // 省略構(gòu)造方法 }

新建com.bjsxt.mapper.UserMapper

package com.bjsxt.mapper;public interface UserMapper {//根據(jù)用戶名查詢用戶信息@Select("select * from t_user where uname=#{uname}")User selUserInfoMapper(@Param("uname") String uname); }

4 編寫業(yè)務(wù)層代碼

新建com.bjsxt.service.UserService及實現(xiàn)類

public interface UserService {//用戶登錄User selUserInfoService(String uname); } @Service public class UserServiceImpl implements UserService {//聲明mapper屬性@Autowiredprivate UserMapper userMapper;//用戶登錄@Overridepublic User selUserInfoService(String uname) {return userMapper.selUserInfoMapper(uname);} }

5 編寫控制器

新建com.bjsxt.controller.UserController

package com.bjsxt.controller;@Controller public class UserController {//聲明service屬性@Autowiredprivate UserService userService;//聲明單元方法:登錄認(rèn)證@RequestMapping("userLogin")public String userLogin(String uname,String pwd){//1.根據(jù)用戶名獲取用戶信息User user=userService.selUserInfoService(uname);//2.判斷用戶名是否合法if(user!=null){//3.校驗密碼if(user.getPwd().equals(pwd)){//認(rèn)證成功return "main";}}return "error";}//聲明公共單元方法完成頁面的內(nèi)部轉(zhuǎn)發(fā)@RequestMapping("{uri}")public String getPage(@PathVariable String uri){return uri;}}

6 編寫啟動類

新建com.bjsxt.ShiroApplication

package com.bjsxt;import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication @MapperScan("com.bjsxt.mapper") public class ShiroApplication {public static void main(String[] args) {SpringApplication.run(ShiroApplication.class,args);}}

7 編寫登錄頁面和主頁面

新建templates/login.html

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><h3>SpringBoot整合Shiro登錄案例</h3><hr><!--創(chuàng)建登錄頁面--><form action="userLogin" method="post">用戶名: <input type="text" name="uname" value=""><br>密碼: <input type="password" name="pwd" value=""><br><input type="submit" value="登錄"></form></body> </html>

新建templates/main.html。

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"> <head><meta charset="UTF-8"><title>Title</title> </head> <body>我是主頁面 </body> </html>

二、 springboot整合shiro實現(xiàn)登錄認(rèn)證和憑證匹配

1 添加依賴

<dependencies><!-- 注釋掉web啟動器是因為shiro-spring-boot-web-starter依賴了spring-boot-starter-web --><!-- <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>--><!--配置shiro的啟動器--><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring-boot-web-starter</artifactId><version>1.4.2</version></dependency></dependencies>

2 自定義Realm

新建com.bjsxt.shiro.MyRealm編寫認(rèn)證邏輯

package com.bjsxt.shiro;//配置為Bean對象 @Component public class MyRealm extends AuthorizingRealm {//聲明業(yè)務(wù)層屬性@Autowiredprivate UserService userService;//自定義授權(quán)策略@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {return null;}//自定義認(rèn)證策略@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {//聲明認(rèn)證代碼//1.獲取用戶傳遞的用戶名信息Object principal = token.getPrincipal();//2.根據(jù)用戶名獲取數(shù)據(jù)庫中的用戶信息User user = userService.selUserInfoService((String) principal);//3.認(rèn)證if(user!=null){//用戶名是正確的//4.認(rèn)證密碼AuthenticationInfo info= new SimpleAuthenticationInfo(principal,user.getPwd(), user.getUname());return info;}return null;} }

3 編寫配置

新建com.bjsxt.config.ShiroConfig,編寫配置

package com.bjsxt.config;@Configuration public class ShiroConfig {//聲明MyRealm屬性@Autowiredprivate MyRealm myRealm;//聲明bean方法@Beanpublic DefaultWebSecurityManager securityManager(){DefaultWebSecurityManager defaultWebSecurityManager=new DefaultWebSecurityManager();defaultWebSecurityManager.setRealm(myRealm);return defaultWebSecurityManager;}

4 userService新增單元方法:使用shiro認(rèn)證

package com.bjsxt.controller;@Controller public class UserController {//聲明單元方法:使用shiro認(rèn)證@RequestMapping("userLogin2")public String userLogin2(String uname,String pwd){//1.獲取subject對象Subject subject = SecurityUtils.getSubject();//2.認(rèn)證//創(chuàng)建認(rèn)證對象存儲認(rèn)證信息AuthenticationToken token= new UsernamePasswordToken(uname,pwd);try{subject.login(token);return "redirect:main";}catch(Exception e){e.printStackTrace();}return "redirect:login";}//聲明公共單元方法完成頁面的內(nèi)部轉(zhuǎn)發(fā)@RequestMapping("{uri}")public String getPage(@PathVariable String uri){return uri;}}

此時登錄出現(xiàn)問題:訪問login時報錯,錯誤說找不到login.jsp,應(yīng)該找的是login.html
解決:在ShiroConfig配置類自定義shiro過濾器參數(shù)bean

package com.bjsxt.config;@Configuration public class ShiroConfig {//自定義shiro過濾器參數(shù)bean@Beanpublic ShiroFilterChainDefinition shiroFilterChainDefinition(){DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();definition.addPathDefinition("/login", "anon");definition.addPathDefinition("/userLogin", "anon");definition.addPathDefinition("/main", "anon");definition.addPathDefinition("/**", "user");return definition;}}

將<form action="userLogin" method="post">改為<form action="userLogin2" method="post">

<body><h3>SpringBoot整合Shiro登錄案例</h3><hr><!--創(chuàng)建登錄頁面--><form action="userLogin2" method="post">用戶名: <input type="text" name="uname" value=""><br>密碼: <input type="password" name="pwd" value=""><br><input type="submit" value="登錄"></form> </body>

啟動測試

5 憑證匹配器

首先將數(shù)據(jù)庫中用戶張三的密碼改為:6bdae6366c1e46d541eb0ca9547d974c

5.1 修改ShiroConfig

@Bean public DefaultWebSecurityManager securityManager() {DefaultWebSecurityManager defaultWebSecurityManager= new DefaultWebSecurityManager();//創(chuàng)建憑證匹配器HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();matcher.setHashAlgorithmName("md5");matcher.setHashIterations(2);myRealm.setCredentialsMatcher(matcher);//將自定義的認(rèn)證策略對象注入到SecurityManagerdefaultWebSecurityManager.setRealm(myRealm);return defaultWebSecurityManager; }

5.2 修改MyRealm

修改MyRealm中doGetAuthenticationInfo方法。

//自定義認(rèn)證策略@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {//聲明認(rèn)證代碼//1.獲取用戶傳遞的用戶名信息Object principal = token.getPrincipal();//2.根據(jù)用戶名獲取數(shù)據(jù)庫中的用戶信息User user = userService.selUserInfoService((String) principal);//3.認(rèn)證if(user!=null){//用戶名是正確的//4.認(rèn)證密碼AuthenticationInfo info= new SimpleAuthenticationInfo(principal,user.getPwd(), ByteSource.Util.bytes(user.getUid()+""),user.getUname());return info;}return null;}

三、 remember me實現(xiàn)—shiro已經(jīng)集成

1 修改application.yml-----增加shiro的loginUrl地址

spring:datasource:driver-class-name: com.mysql.jdbc.Driverusername: rooturl: jdbc:mysql://localhost:3306/springboot-loginpassword: 1234 ##配置mapper的xml文件的路徑 mybatis:mapper-locations: classpath:mybatis/*.xml shiro:##當(dāng)用戶訪問某個需要登錄的功能時,但是被shiro內(nèi)置的過濾器攔截后,判斷本次請求##沒有登錄,而是直接訪問的,則重定向到loginUrl的路徑資源響應(yīng)給用戶loginUrl: /login

2 增加記住我的按鈕

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><h3>SpringBoot整合Shiro登錄案例</h3><hr><!--創(chuàng)建登錄頁面--><form action="userLogin2" method="post">用戶名: <input type="text" name="uname" value=""><br>密碼: <input type="password" name="pwd" value=""><br><input type="submit" value="登錄">&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" name="rememberme" value="true">記住俺</form></body> </html>

3 修改Controller

@RequestMapping("userLogin2")public String userLogin2(String uname,String pwd,@RequestParam(defaultValue = "false") Boolean rememberme){//1.獲取subject對象Subject subject = SecurityUtils.getSubject();//2.認(rèn)證//創(chuàng)建認(rèn)證對象存儲認(rèn)證信息AuthenticationToken token= new UsernamePasswordToken(uname,pwd,rememberme);try{subject.login(token);return "redirect:main";}catch(Exception e){e.printStackTrace();}return "redirect:login";}

4 修改ShiroConfig

@Beanpublic DefaultWebSecurityManager securityManager(){DefaultWebSecurityManager defaultWebSecurityManager=new DefaultWebSecurityManager();//創(chuàng)建憑證匹配器HashedCredentialsMatcher matcher=new HashedCredentialsMatcher();//設(shè)置匹配器的加密算法matcher.setHashAlgorithmName("md5");//設(shè)置匹配器的迭代加密次數(shù)matcher.setHashIterations(2);//將匹配器注入到自定義的認(rèn)證策略對象中myRealm.setCredentialsMatcher(matcher);//將自定義的認(rèn)證策略對象注入到SecurityManagerdefaultWebSecurityManager.setRealm(myRealm);//將CookieRememberMeManager對象注入到SecurityManager,開啟了rememberme功能defaultWebSecurityManager.setCacheManager(ehCacheManager());return defaultWebSecurityManager;}//設(shè)置Cookie的信息public SimpleCookie rememberMeCookie(){SimpleCookie simpleCookie=new SimpleCookie("rememberMe");//設(shè)置有效路徑simpleCookie.setPath("/");//設(shè)置聲明周期simpleCookie.setMaxAge(30*24*60*60);//返回設(shè)置的cookiereturn simpleCookie;}//創(chuàng)建rememberMeManager對象public CookieRememberMeManager rememberMeManager(){//創(chuàng)建CookieRememberMeManager對象CookieRememberMeManager cookieRememberMeManager=new CookieRememberMeManager();//注入Cookie對象cookieRememberMeManager.setCookie(rememberMeCookie());//設(shè)置密鑰cookieRememberMeManager.setCipherKey(Base64.decode("MTIzNDU2Nzg="));//返回return cookieRememberMeManager;}//自定義shiro過濾器參數(shù)bean----`definition.addPathDefinition("/**", "user");`@Beanpublic ShiroFilterChainDefinition shiroFilterChainDefinition(){DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();definition.addPathDefinition("/login", "anon");definition.addPathDefinition("/userLogin2", "anon");//開啟shiro內(nèi)置的退出過濾器,完成退出功能definition.addPathDefinition("/logout", "logout");//definition.addPathDefinition("/main", "anon");definition.addPathDefinition("/**", "user");return definition;}

四、 配置退出

1 修改配置類

修改ShiroConfig類,添加logout filter 對應(yīng)的url。definition.addPathDefinition("/logout", "logout");

@Bean public ShiroFilterChainDefinition shiroFilterChainDefinition() {DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();definition.addPathDefinition("/doLogin", "anon");definition.addPathDefinition("/logout", "logout");definition.addPathDefinition("/**", "authc");return definition; }

2 修改主頁面

在index.html頁面中添加超鏈接。跳轉(zhuǎn)到/logout后會由shiro內(nèi)置filter進(jìn)行攔截。

<body> index.html <a href="/logout">退出</a> </body>

五、 授權(quán)

1 簡介

授權(quán)就是判斷認(rèn)證用戶是否具有指定角色或指定權(quán)限。
Shiro可以和JSP整合也可以和Thymeleaf整合,我們講解SpringBoot的視圖技術(shù)Thymeleaf整合Shiro。
只要是授權(quán)就執(zhí)行Realm的doGetAuthorizationInfo進(jìn)行判斷,而觸發(fā)doGetAuthorizationInfo的方式,常用的就兩種:
(1)在頁面中通過shiro:xxxx 屬性進(jìn)行判斷
(2)在java代碼中通過注解@RequiresXXX

thymeleaf中常用屬性

需要在html頁面中添加屬性

<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">

1.1 shiro:user=””
認(rèn)證通過或已記住的用戶。
1.2 shiro:authenticated=””
認(rèn)證通過的用戶。不包含記住的用戶。
1.3 shiro:principal
輸出認(rèn)證用戶信息。shiro:principal/
1.4 shiro:hasRole=“admin”
判斷是否具有指定角色。
1.5 shiro:lacksRole=“admin”
判斷是否不是沒有指定角色。
1.6 shiro:hasAllRoles=“role1,role2”
判斷指定角色用戶是否都具有。
1.7 shiro:hasAnyRoles=“role1,role2”
只要用戶具有其中一個角色就表示判斷通過。
1.8 shiro:hasPermission=“userInfo:add”
是否具有指定權(quán)限。
1.9 shiro:lacksPermission=“userInfo:del”
是否不具有指定權(quán)限
1.10 shiro:hasAllPermissions=“userInfo:view, userInfo:add”
是否全具有指定權(quán)限。
1.11 shiro:hasAnyPermissions=“userInfo:view, userInfo:del”
只要有其中任何一個權(quán)限即可。

2 Thymeleaf整合shiro

2.1 添加依賴

<dependency><groupId>com.github.theborakompanioni</groupId><artifactId>thymeleaf-extras-shiro</artifactId><version>2.0.0</version> </dependency>

2.2 修改配置類(負(fù)責(zé)解析thymeleaf中shiro的相關(guān)屬性)

//創(chuàng)建解析Thymeleaf中的shiro屬性的對象,由SpringBoot項目底層自動調(diào)用@Beanpublic ShiroDialect shiroDialect() {return new ShiroDialect();}

2.3 修改Realm

綁定用戶具有的角色和權(quán)限,相關(guān)數(shù)據(jù)應(yīng)該是從數(shù)據(jù)庫中取出。

//自定義授權(quán)策略@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {//1.從數(shù)據(jù)庫中獲取用戶的權(quán)限信息//2.將權(quán)限信息存儲到shiro授權(quán)對象中System.out.println("我是授權(quán)認(rèn)證方法,我被執(zhí)行了");SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();info.addRole("role1");info.addRole("role2");info.addStringPermission("user:insert");info.addStringPermission("user:update");info.addStringPermission("sys:*");return info;}

2.4 修改main.html

訪問頁面后會發(fā)現(xiàn)“有角色”不顯示,“有權(quán)限”顯示。

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"> <head><meta charset="UTF-8"><title>Title</title> </head> <body>我是主頁面<a href="/logout">退出</a><hr><span shiro:hasRole="role3">有角色</span><br><span shiro:user="">shiro:user=””認(rèn)證通過或已記住的用戶</span><br><span shiro:authenticated="">shiro:authenticated=””認(rèn)證通過的用戶。不包含記住的用戶。</span><br><hr><a href="/demo">測試后臺邏輯代碼的授權(quán)</a></body> </html>

3 使用注解判斷方法是否具有權(quán)限執(zhí)行

方法:可以用控制器方法,也可以是業(yè)務(wù)方法。常在控制器方法上添加注解進(jìn)行判斷。
常用注解:
(1)@RequiresPermissions("") 必須具有指定權(quán)限
(2)@RequiresAuthentication 必須已經(jīng)認(rèn)證
(3)@RequiresRoles("") 必須具有指定角色
(4)@RequiresUser 必須是已認(rèn)證或記住用戶
(5)@RequiresGuest 必須是訪客

3.1 修改main.html

添加下面內(nèi)容

<a href="/isPermission">跳轉(zhuǎn)到判斷權(quán)限的控制器</a>

3.2 修改UserController類

@RequestMapping("/isPermission") @ResponseBody @RequiresPermissions("abc:jqk") public String isPermission(){return "OK"; }

當(dāng)用戶登錄成后,點擊超鏈接“跳轉(zhuǎn)到判斷權(quán)限的”超鏈接會出現(xiàn)500錯誤頁面信息。

3.3 新建依賴處理類

新建com.bjsxt.controller.NoPermissionException

@ControllerAdvice public class NoPermissionException {@ResponseBody@ExceptionHandler(UnauthorizedException.class)public String handleShiroException(Exception ex) {return "無權(quán)限";}@ResponseBody@ExceptionHandler(AuthorizationException.class)public String AuthorizationException(Exception ex) {return "權(quán)限認(rèn)證失敗";} }

六 EHCache

1 ehcache簡介

EHCache是sourceforge的開源緩存項目,現(xiàn)已經(jīng)具有獨立官網(wǎng),網(wǎng)址:(http://www.ehcache.org)。其本身是純JAVA實現(xiàn)的,所以可以和絕大多數(shù)Java項目無縫整合,例如:Hibernate的緩存就是基于EHCache實現(xiàn)的。
EHCache支持內(nèi)存和磁盤緩存,默認(rèn)是存儲在內(nèi)存中的,當(dāng)內(nèi)存不夠時允許把緩存數(shù)據(jù)同步到磁盤中,所以不需要擔(dān)心內(nèi)存不夠問題。
EHCache支持基于Filter的Cache實現(xiàn),同時也支持Gzip壓縮算法提高響應(yīng)速度。

2 EHCache API演示

2.1 添加依賴

從3.0版本開始groupid為org.ehcache

<dependencies><dependency><groupId>net.sf.ehcache</groupId><artifactId>ehcache</artifactId><version>2.6.11</version></dependency> </dependencies>

2.2 新建配置文件

在src/main/resources中新建ehcache.xml。
屬性含義:
maxElementsInMemory:緩存中允許創(chuàng)建的最大對象數(shù)。
eternal:緩存中對象是否為永久的,如果是,超時設(shè)置將被忽略,對象從不過期。
timeToIdleSeconds:緩存數(shù)據(jù)的鈍化時間,取值0表示無限長。
timeToLiveSeconds:緩存數(shù)據(jù)的生存時間,取值0表示無限長。
overflowToDisk:內(nèi)存不足時,是否啟用磁盤緩存。
memoryStoreEvictionPolicy:緩存滿了之后的淘汰算法。

<?xml version="1.0" encoding="UTF-8"?> <ehcache><!-- 磁盤緩存位置 --><diskStore path="java.io.tmpdir/ehcache"/><!-- 默認(rèn)緩存 --><defaultCachemaxEntriesLocalHeap="10000"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"maxEntriesLocalDisk="10000000"diskExpiryThreadIntervalSeconds="120"memoryStoreEvictionPolicy="LRU"><persistence strategy="localTempSwap"/></defaultCache><!-- helloworld緩存 --><cache name="HelloWorldCache"maxElementsInMemory="1000"eternal="false"timeToIdleSeconds="5"timeToLiveSeconds="5"overflowToDisk="false"memoryStoreEvictionPolicy="LRU"/> </ehcache>

七 Shiro和EhCache整合

Shiro支持很多第三方緩存工具。官方提供了shiro-ehcache,實現(xiàn)了把EHCache當(dāng)做Shiro的緩存工具的解決方案。其中最好用的一個功能是就是緩存認(rèn)證執(zhí)行的Realm方法,減少對數(shù)據(jù)庫的訪問。

1 添加依賴

添加shiro-ehcache依賴。
commons-io主要是為了使用里面的工具類。本質(zhì)和當(dāng)前整合功能沒有關(guān)系。

<dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-ehcache</artifactId><version>1.4.2</version> </dependency> <dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.6</version> </dependency>

2 編寫ehcache緩存配置

在resources下新建ehcache/ehcache-shiro.xml

<?xml version="1.0" encoding="UTF-8"?> <ehcache name="ehcache" updateCheck="false"><!-- 磁盤緩存位置 --> <diskStore path="java.io.tmpdir"/> <!-- 默認(rèn)緩存 --> <defaultCachemaxEntriesLocalHeap="1000"eternal="false"timeToIdleSeconds="3600"timeToLiveSeconds="3600"overflowToDisk="false"> </defaultCache><!-- 登錄記錄緩存 鎖定10分鐘 --> <cache name="loginRecordCache"maxEntriesLocalHeap="2000"eternal="false"timeToIdleSeconds="600"timeToLiveSeconds="0"overflowToDisk="false"statistics="true"> </cache></ehcache>

3 修改配置文件

@Bean public DefaultWebSecurityManager securityManager() {DefaultWebSecurityManager manager = new DefaultWebSecurityManager();HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();hashedCredentialsMatcher.setHashAlgorithmName("md5");hashedCredentialsMatcher.setHashIterations(2);myRealm.setCredentialsMatcher(hashedCredentialsMatcher);manager.setRealm(myRealm);manager.setRememberMeManager(rememberMeManager());manager.setCacheManager(getEhCacheManager());return manager; }@Bean public EhCacheManager ehCacheManager(){EhCacheManager ehCacheManager = new EhCacheManager();InputStream is = null;try {is = ResourceUtils.getInputStreamForPath("classpath:ehcache/ehcache-shiro.xml");} catch (IOException e) {e.printStackTrace();}net.sf.ehcache.CacheManager cacheManager = new net.sf.ehcache.CacheManager(is);ehCacheManager.setCacheManager(cacheManager);return ehCacheManager; }

八 Shiro中Session對象獲取

Session session = SecurityUtils.getSubject().getSession(); session.setAttribute("key","value");

總結(jié)

以上是生活随笔為你收集整理的SpringBoot整合Shiro实现登录认证和授权CHCache的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。