成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)

瀏覽:129日期:2022-08-14 13:39:24
Shiro簡(jiǎn)介 Apache Shiro是一個(gè)強(qiáng)大且易用的Java安全框架,執(zhí)行身份驗(yàn)證、授權(quán)、密碼和會(huì)話管理 三個(gè)核心組件:Subject, SecurityManager 和 Realms Subject代表了當(dāng)前用戶的安全操作 SecurityManager管理所有用戶的安全操作,是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ì)用戶執(zhí)行認(rèn)證(登錄)和授權(quán)(訪問(wèn)控制)驗(yàn)證時(shí),Shiro會(huì)從應(yīng)用配置的Realm中查找用戶及其權(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)入依賴

<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

快速入門(mén)實(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三大對(duì)象:Subject: 用戶SecurityManager:管理所有用戶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í)例:// 在類路徑的根目錄下使用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)前用戶對(duì)象 SubjectSubject currentUser = SecurityUtils.getSubject();// 使用Session做一些事情(不需要Web或EJB容器!!!Session session = currentUser.getSession();//通過(guò)當(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 : 令牌,沒(méi)有獲取,隨機(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.'); } // ... 在此處捕獲更多異常(也許是針對(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();//注銷System.exit(0);//退出 }}

啟動(dòng)測(cè)試

Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)

SpringBoot-Shiro整合(最后會(huì)附上完整代碼)

前期工作

導(dǎo)入shiro-spring整合包依賴

<!-- 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='http://www.piao2010.com/bcjs/@{/user/add}' rel='external nofollow' rel='external nofollow' rel='external nofollow' >add</a>| <a th:href='http://www.piao2010.com/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>

編寫(xiě)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對(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;@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'; }}

Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)

實(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)到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頁(yè)面跳轉(zhuǎn)

@RequestMapping('/toLogin') public String login(){return 'login'; }

上面,我們已經(jīng)成功攔截了,現(xiàn)在我們來(lái)實(shí)現(xiàn)用戶認(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}'> 用戶名:<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)前的用戶Subject subject = SecurityUtils.getSubject();//封裝用戶數(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','用戶名錯(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)行測(cè)試,成功!!!

附上最后的完整代碼

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>首頁(yè)</title></head><body><h1>首頁(yè)</h1><p th:text='${msg}'></p><a th:href='http://www.piao2010.com/bcjs/@{/user/add}' rel='external nofollow' rel='external nofollow' rel='external nofollow' >add</a>| <a th:href='http://www.piao2010.com/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í)行登陸操作,沒(méi)有發(fā)生異常就說(shuō)明登陸成功 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)置過(guò)濾器 anon無(wú)需授權(quán)、登錄就可以訪問(wèn),所有人可訪。 authc 需要登錄授權(quán)才能訪問(wèn)。 authcBasicBasic HTTP身份驗(yàn)證攔截器 logout退出攔截器。退出成功后,會(huì) redirect到設(shè)置的/URI noSessionCreation不創(chuàng)建會(huì)話連接器 perms授權(quán)攔截器,擁有對(duì)某個(gè)資源的權(quán)限才可訪問(wèn) port端口攔截器 restrest風(fēng)格攔截器 roles角色攔截器,擁有某個(gè)角色的權(quán)限才可訪問(wèn) sslssl攔截器。通過(guò)https協(xié)議才能通過(guò) user用戶攔截器,需要有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)到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對(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;//拋出異常 用戶名錯(cuò)誤那個(gè)異常}//密碼認(rèn)證,shiro自己做return new SimpleAuthenticationInfo('',password,''); }}

但是,我們?cè)谟脩粽J(rèn)證這里,真實(shí)情況是從數(shù)據(jù)庫(kù)中取的,所以,我們接下來(lái)去實(shí)現(xiàn)一下從數(shù)據(jù)庫(kù)中取出數(shù)據(jù)來(lái)實(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ù)庫(kù)編寫(xiě)實(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;}

編寫(xiě)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);}

編寫(xiě)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>

編寫(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;@Servicepublic 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;//拋出異常 用戶名錯(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)證不了;

Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)

運(yùn)行測(cè)試:add頁(yè)面無(wú)法訪問(wèn)

Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)

授權(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)行效果:

Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)

從數(shù)據(jù)庫(kù)中接受用戶的權(quán)限,進(jìn)行判斷

在數(shù)據(jù)庫(kù)中添加一個(gè)屬性perms,相應(yīng)的實(shí)體類也要修改

Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)

Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)

修改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è)置的用戶權(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)前用戶的權(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;//拋出異常 用戶名錯(cuò)誤那個(gè)異常}//密碼認(rèn)證,shiro自己做return new SimpleAuthenticationInfo(user,user.getPwd(),''); }}

Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)

有了授權(quán)后,就又出現(xiàn)了一個(gè)問(wèn)題,我們是不是要讓用戶沒(méi)有權(quán)限的東西,就看不見(jià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: 用來(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><!--判斷是否有用戶登錄,如果有就不顯示登錄按鈕--><div th:if='${session.loginUser==null}'> <a th:href='http://www.piao2010.com/bcjs/@{/toLogin}' rel='external nofollow' >登錄</a></div><div shiro:hasPermission='user:add'> <a th:href='http://www.piao2010.com/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.piao2010.com/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);

測(cè)試

以上就是Java安全框架——Shiro的使用詳解(附springboot整合Shiro的demo)的詳細(xì)內(nèi)容,更多關(guān)于Java安全框架——Shiro的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Java
相關(guān)文章:
成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久
亚洲欧美日韩精品在线| 日本高清不卡视频| 色综合久久久久综合体桃花网| 国产精品久久久久久久久果冻传媒| 国产精品18久久久久久久久| 欧洲在线/亚洲| 日韩黄色小视频| 亚洲一区二区高清视频| 久久久一区二区| 99久久99久久综合| 制服丝袜中文字幕一区| 蜜臀av在线播放一区二区三区| 国产三级精品在线不卡| 亚洲欧美日韩国产中文在线| 亚洲国产电影| 一区av在线播放| 亚洲欧美日韩另类精品一区二区三区| 亚洲视频在线一区| 亚洲视频成人| 夜夜揉揉日日人人青青一国产精品 | 美女mm1313爽爽久久久蜜臀| 91国偷自产一区二区三区观看| 免费日韩伦理电影| 精品视频一区二区不卡| 国产一区二区三区四区五区美女 | 欧美日韩在线三区| 激情综合色播五月| 欧美巨大另类极品videosbest| 国产一区视频在线看| 日韩一区二区三区av| 国产精品自拍毛片| 日韩欧美亚洲国产另类| 成人av免费在线观看| 久久久三级国产网站| 91天堂素人约啪| 国产午夜精品一区二区三区嫩草| 91视频国产观看| 国产精品丝袜一区| 亚洲欧洲一级| 五月婷婷另类国产| 在线精品视频免费观看| 久久99国产精品久久99果冻传媒| 欧美日本国产一区| 懂色一区二区三区免费观看| 久久欧美一区二区| 亚洲精品乱码| 另类欧美日韩国产在线| 欧美一区二区播放| 91网站最新地址| 亚洲欧美日本韩国| 色噜噜狠狠色综合中国| 国产乱码精品一区二区三区五月婷| 91精品国产品国语在线不卡| 99re热视频精品| 亚洲视频在线一区二区| 日本道精品一区二区三区| 国产一区二区免费视频| 久久亚区不卡日本| 亚洲精品韩国| 午夜精品久久久久久久99樱桃 | 国内一区二区三区在线视频| 一区二区三区高清| 欧美精品色一区二区三区| 欧美一区亚洲| 五月激情丁香一区二区三区| 欧美日韩国产综合视频在线观看| 不卡视频免费播放| 综合激情成人伊人| 一本一道波多野结衣一区二区| 国产一区二区三区精品欧美日韩一区二区三区 | 亚洲资源av| 国内精品国产三级国产a久久| 久久久99精品久久| 另类av一区二区| 国产精品一区二区你懂的| 欧美激情一区二区三区不卡 | 久久成人在线| 丁香亚洲综合激情啪啪综合| 国产精品福利一区| 欧美日韩中文国产| 欧美日韩一区在线视频| 性久久久久久久久久久久| 日韩欧美三级在线| 国产美女一区| 国产高清精品久久久久| 日韩一区日韩二区| 欧美日韩成人综合天天影院 | 在线亚洲高清视频| 99久久er热在这里只有精品66| 亚洲一区二区影院| 久久一区二区三区超碰国产精品| 国产精品自拍av| 亚洲影院理伦片| 一本色道精品久久一区二区三区| 日本人妖一区二区| 中文字幕av一区二区三区高| 久久久水蜜桃av免费网站| 成人白浆超碰人人人人| 一级做a爱片久久| 日韩精品一区二区三区四区| 一本一本a久久| 成熟亚洲日本毛茸茸凸凹| 国产精品福利一区二区三区| 欧美日韩精品综合在线| 激情综合亚洲| 国产精品自拍在线| 亚洲国产欧美日韩另类综合| 日韩网站在线看片你懂的| 99视频精品免费观看| 风间由美一区二区av101| 亚洲午夜免费福利视频| 久久―日本道色综合久久| 久久精品一本| 欧美伊人影院| 国产一区二区三区在线观看免费 | 亚洲高清视频一区二区| 一本久久综合亚洲鲁鲁五月天| 欧美日韩在线综合| 另类小说图片综合网| 亚洲欧美精品| 久久久精品国产99久久精品芒果| 国产乱码精品一区二区三| 欧美久久久久中文字幕| 麻豆精品视频在线观看免费| 亚洲永久字幕| 欧美电视剧免费观看| 亚洲一区二区三区四区在线 | 国产日韩欧美一区二区三区在线观看| 国产成人精品综合在线观看 | 精品美女被调教视频大全网站| 色噜噜狠狠一区二区三区果冻| 红桃视频欧美| 国产suv精品一区二区三区| 日韩电影网1区2区| 亚洲女人的天堂| 国产喷白浆一区二区三区| 日韩一级高清毛片| 欧美在线制服丝袜| 亚洲欧美不卡| 999亚洲国产精| 午夜欧美精品| 成人黄色在线视频| 国产综合成人久久大片91| 视频一区二区欧美| 亚洲一区二区视频| 亚洲激情六月丁香| 国产精品国产三级国产aⅴ入口| 精品国产乱码久久久久久浪潮| 欧美亚一区二区| 一本大道av一区二区在线播放| 一本色道久久99精品综合| 黄色另类av| 国产精品hd| 欧美jjzz| 色综合中文综合网| 亚洲色图20p| 国产精品久久久久影视| 久久久一区二区三区| 欧美电影免费观看高清完整版在| 777a∨成人精品桃花网| 在线国产电影不卡| 久久一区视频| 久久精选视频| 久久蜜桃资源一区二区老牛| 久久精品动漫| 一本大道久久a久久综合婷婷| 久久久www免费人成黑人精品| 先锋亚洲精品| 亚洲二区免费| 亚洲国产一区二区三区a毛片| 极品日韩久久| 在线欧美福利| 亚洲午夜视频| 亚洲免费观看| 一区二区三区福利| 亚洲视频1区| 麻豆av一区二区三区久久| 亚洲专区免费| 久久久久久精| 欧美性色欧美a在线播放| 在线免费不卡电影| 欧美天天综合网| 欧美日韩中文字幕一区| 欧美色男人天堂| 欧美午夜片在线看| 欧美日产在线观看| 欧美一二三区精品| 久久综合999| 国产偷国产偷亚洲高清人白洁| 久久精品视频网| 中文字幕一区二区三区视频| 最新不卡av在线| 一区二区三区精品视频| 五月天精品一区二区三区| 久久国产精品第一页| 国产精品白丝av| 99久久精品99国产精品| 欧美久久视频| 日韩视频精品| 久久久久久久久久久久久9999|