Shiro簡介
什麼是Shiro
Apache Shiro 是一個Java 的安全(權限)框架。
Shiro 可以非常容易的開發出足夠好的應用,其不僅可以用在JavaSE環境,也可以用在JavaEE環境。
Shiro可以完成,認證,授權,加密,會話管理,Web集成,緩存等。
有哪些功能
Authentication:身份認證,登錄,驗證用戶是不是擁有相應的身份;
Authorization:授權,即權限驗證,驗證某個已認證的用戶是否擁有某個權限,即判斷用戶能否 進行什麼操作,如:驗證某個用戶是否擁有某個角色,或者細粒度的驗證某個用戶對某個資源是否 具有某個權限!
Session Manager:會話管理,即用戶登錄後就是第一次會話,在沒有退出之前,它的所有信息都 在會話中;會話可以是普通的JavaSE環境,也可以是Web環境;
Cryptography:加密,保護數據的安全性,如密碼加密存儲到數據庫中,而不是明文存儲;
Web Support:Web支持,可以非常容易的集成到Web環境;
Caching:緩存,比如用戶登錄後,其用戶信息,擁有的角色、權限不必每次去查,這樣可以提高 效率
Concurrency:Shiro支持多線程應用的併發驗證,即,如在一個線程中開啓另一個線程,能把權限 自動的傳播過去
Testing:提供測試支持;
Run As:允許一個用戶假裝爲另一個用戶(如果他們允許)的身份進行訪問;
Remember Me:記住我,這個是非常常見的功能,即一次登錄後,下次再來的話不用登錄了
Shiro架構(外部)
從外部來看Shiro,即從應用程序角度來觀察如何使用shiro完成工作:
- subject: 應用代碼直接交互的對象是Subject,也就是說Shiro的對外API核心就是Subject, Subject代表了當前的用戶,這個用戶不一定是一個具體的人,與當前應用交互的任何東西都是 Subject,如網絡爬蟲,機器人等,與Subject的所有交互都會委託給SecurityManager;Subject其 實是一個門面,SecurityManageer 纔是實際的執行者
- SecurityManager:安全管理器,即所有與安全有關的操作都會與SercurityManager交互,並且它 管理着所有的Subject,可以看出它是Shiro的核心,它負責與Shiro的其他組件進行交互,它相當於 SpringMVC的DispatcherServlet的角色
- Realm:Shiro從Realm獲取安全數據(如用戶,角色,權限),就是說SecurityManager 要驗證用戶身份,那麼它需要從Realm 獲取相應的用戶進行比較,來確定用戶的身份是否合法;也需要從 Realm 得到用戶相應的角色、權限,進行驗證用戶的操作是否能夠進行,可以把Realm看成 DataSource;
Shiro架構(內部)
- Subject:任何可以與應用交互的 “用戶”;
- Security Manager:相當於SpringMVC中的DispatcherServlet;是Shiro的心臟,所有具體的交互 都通過Security Manager進行控制,它管理者所有的Subject,且負責進行認證,授權,會話,及緩存的管理。
- Authenticator:負責Subject認證,是一個擴展點,可以自定義實現;可以使用認證策略 (Authentication Strategy),即什麼情況下算用戶認證通過了;
- Authorizer:授權器,即訪問控制器,用來決定主體是否有權限進行相應的操作;即控制着用戶能 訪問應用中的那些功能;
- Realm:可以有一個或者多個的realm,可以認爲是安全實體數據源,即用於獲取安全實體的,可 以用JDBC實現,也可以是內存實現等等,由用戶提供;所以一般在應用中都需要實現自己的realm
- SessionManager:管理Session生命週期的組件,而Shiro並不僅僅可以用在Web環境,也可以用 在普通的JavaSE環境中
- CacheManager:緩存控制器,來管理如用戶,角色,權限等緩存的;因爲這些數據基本上很少改變,放到緩存中後可以提高訪問的性能;
- Cryptography:密碼模塊,Shiro 提高了一些常見的加密組件用於密碼加密,解密等
HelloWorld
快速實踐
查看官網文檔:http://shiro.apache.org/tutorial.html
官方的quickstart:https://github.com/apache/shiro/tree/master/samples/quickstart/
1、創建一個maven父工程,用於學習Shiro,刪掉不必要的東西
2、創建一個普通的Maven子工程:hello-shiro
3、根據官方文檔,我們來導入Shiro的依賴
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.5.1</version>
</dependency>
<!-- configure logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<scope>runtime</scope>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
4、編寫Shiro配置
log4j.properties
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
shiro.ini
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
# =============================================================================
# Quickstart INI Realm configuration
#
# For those that might not understand the references in this file, the
# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
# =============================================================================
# -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
5、編寫我們的QuickStrat
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
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;
/**
* Simple Quickstart application showing how to use Shiro's API.
*
* @since 0.9 RC2
*/
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
// The easiest way to create a Shiro SecurityManager with configured
// realms, users, roles and permissions is to use the simple INI config.
// We'll do that by using a factory that can ingest a .ini file and
// return a SecurityManager instance:
// Use the shiro.ini file at the root of the classpath
// (file: and url: prefixes load from files and urls respectively):
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
// for this simple example quickstart, make the SecurityManager
// accessible as a JVM singleton. Most applications wouldn't do this
// and instead rely on their container configuration or web.xml for
// webapps. That is outside the scope of this simple quickstart, so
// we'll just do the bare minimum so you can continue to get a feel
// for things.
SecurityUtils.setSecurityManager(securityManager);
// Now that a simple Shiro environment is set up, let's see what you can do:
// get the currently executing user:
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// let's login the current user so we can check against roles and permissions:
if (!currentUser.isAuthenticated()) {
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 more exceptions here (maybe custom ones specific to your application?
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);
}
}
6、測試運行一下
7、如果報錯,則導入一下 commons-logging 的依賴
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
8、默認的日誌消息!
閱讀代碼
1、導入了一堆包!
2、類的描述
/**
* Simple Quickstart application showing how to use Shiro's API.
* 簡單的快速啓動應用程序,演示如何使用Shiro的API。
*/
3、通過工廠模式創建 SecurityManager 的實例對象
// The easiest way to create a Shiro SecurityManager with configured
// realms, users, roles and permissions is to use the simple INI config.
// We'll do that by using a factory that can ingest a .ini file and
// return a SecurityManager instance:
// 使用類路徑根目錄下的shiro.ini文件
// Use the shiro.ini file at the root of the classpath
// (file: and url: prefixes load from files and urls respectively):
Factory<SecurityManager> factory = new
IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
// for this simple example quickstart, make the SecurityManager
// accessible as a JVM singleton. Most applications wouldn't do this
// and instead rely on their container configuration or web.xml for
// webapps. That is outside the scope of this simple quickstart, so
// we'll just do the bare minimum so you can continue to get a feel
// for things.
SecurityUtils.setSecurityManager(securityManager);
// 現在已經建立了一個簡單的Shiro環境,讓我們看看您可以做什麼:
// Now that a simple Shiro environment is set up, let's see what you can
do:
4、獲取當前的Subject
// get the currently executing user: 獲取當前正在執行的用戶
Subject currentUser = SecurityUtils.getSubject();
5、session的操作
// 用會話做一些事情(不需要web或EJB容器!!!)
// Do some stuff with a Session (no need for a web or EJB container!!!)
Session session = currentUser.getSession(); // 獲得session
session.setAttribute("someKey", "aValue"); // 設置Session的值!
String value = (String) session.getAttribute("someKey"); // 從session中獲取值
if (value.equals("aValue")) { //判斷session中是否存在這個值!
log.info("==Retrieved the correct value! [" + value + "]");
}
6、用戶認證功能
// 測試當前的用戶是否已經被認證,即是否已經登錄!
// let's login the current user so we can check against roles and permissions:
if (!currentUser.isAuthenticated()) { // isAuthenticated();是否認證
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); // 將用戶名和密碼封裝爲 UsernamePasswordToken
token.setRememberMe(true); // 記住我功能
try {
currentUser.login(token); // 執行登錄,可以登錄成功的!
} catch (UnknownAccountException uae) { // 如果沒有指定的用戶,則 UnknownAccountException異常
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 more exceptions here (maybe custom ones specific to your application?
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.");
7、角色檢查
//test a role:
//是否存在某一個角色
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
8、權限檢查,粗粒度
//測試用戶是否具有某一個權限,行爲
//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.");
}
9、權限檢查,細粒度
//測試用戶是否具有某一個權限,行爲,比上面更加的具體!
//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!");
}
10、註銷操作
//執行註銷操作!
//all done - log out!
currentUser.logout();
11. 退出系統 System.exit(0)
SpringBoot集成
準備工作
1、搭建一個SpringBoot項目、選中web模塊即可!
2、導入Maven依賴
<!-- Subject: 用戶-->
<!-- SecurityManaget 管理所有用戶-->
<!-- Realm: 連接數據-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.5.1</version>
</dependency>
<!-- shiro-thymeleaf -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</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.1.21</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3、編寫一個頁面 index.html ( templates )
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首頁</h1>
<p th:text="${msg}"></p>
</body>
</html>
4、編寫 controller 進行訪問測試
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","hello-Shiro");
return "index";
}
}
測試訪問首頁
整合Shiro
回顧核心API:
- Subject:用戶主體
- SecurityManager:安全管理器
- Realm:Shiro 連接數據
1、導入Shiro 和 spring整合的依賴( 準備工作已導入 )
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.5.1</version>
</dependency>
2、 編寫Shiro 配置類 config包
@Configuration
public class ShiroConfig {
// 創建 ShiroFilterFactoryBean (3)
// 創建 DafaultWebSecurityManager (2)
// 創建 realm 對象,需要自定義 (1)
}
3、我們倒着來,先想辦法創建一個 realm(1) 對象
4、我們需要自定義一個 realm 的類,用來編寫一些查詢的方法,或者認證與授權的邏輯
public class UserRealm extends AuthorizingRealm {
// 執行授權邏輯
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("授權--------------------------------------------------------------");
return null;
}
// 執行認證邏輯
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("認證--------------------------------------------------------------");
return null;
}
}
5. 將這個類註冊到我們的Bean中! ShiroConfig
@Configuration
public class ShiroConfig {
// 創建 ShiroFilterFactoryBean (3)
// 創建 DafaultWebSecurityManager (2)
// 創建 realm 對象,需要自定義 (1)
@Bean()
public UserRealm userRealm() {
return new UserRealm();
}
}
6、接下來我們該去創建 DefaultWebSecurityManager(2) 了
@Configuration
public class ShiroConfig {
// 創建 ShiroFilterFactoryBean (3)
// 創建 DafaultWebSecurityManager (2)
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 關聯 Realm
securityManager.setRealm(userRealm);
return securityManager;
}
// 創建 realm 對象,需要自定義 (1)
@Bean()
public UserRealm userRealm() {
return new UserRealm();
}
}
7. 接下來我們該去創建 ShiroFilterFactoryBean(3) 了
@Configuration
public class ShiroConfig {
// 創建 ShiroFilterFactoryBean (3)
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//設置安全管理器
bean.setSecurityManager(securityManager);
return bean;
}
// 創建 DafaultWebSecurityManager (2)
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 關聯 Realm
securityManager.setRealm(userRealm);
return securityManager;
}
// 創建 realm 對象,需要自定義 (1)
@Bean()
public UserRealm userRealm() {
return new UserRealm();
}
}
頁面攔截實現
1、編寫兩個頁面、在templates目錄下新建一個 user 目錄
add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>add</title>
</head>
<body>
<h1>add</h1>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>update</title>
</head>
<body>
<h1>update</h1>
</body>
</html>
2、編寫跳轉到頁面的controller
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(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";
}
}
3、在index頁面上,增加 add 和 update 的跳轉鏈接
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
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>
<a th:href="@{/user/add}">add</a>
</div>
<div>
<a th:href="@{/user/update}">update</a>
</div>
</body>
</html>
4、測試頁面跳轉是否OK
5、準備添加Shiro的內置過濾器
@Configuration
public class ShiroConfig {
// 創建 ShiroFilterFactoryBean (3)
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//設置安全管理器
bean.setSecurityManager(securityManager);
//添加 shiro 的內置過濾器
/*
anon: 無需認證就可以訪問
authc: 必須認證了才能訪問
user: 必須擁有 “記住我” 功能才能用
perms: 擁有對某個資源的權限才能訪問
role: 擁有某個角色權限才能訪問
*/
Map<String, String> filterMap = new LinkedHashMap<>();
//攔截
filterMap.put("/user/add", "authc");
filterMap.put("/user/update", "authc");
bean.setFilterChainDefinitionMap(filterMap);
return bean;
}
// 創建 DafaultWebSecurityManager (2)
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 關聯 Realm
securityManager.setRealm(userRealm);
return securityManager;
}
// 創建 realm 對象,需要自定義 (1)
@Bean()
public UserRealm userRealm() {
return new UserRealm();
}
}
6. 再起啓動測試,訪問鏈接進行測試!攔截OK!但是發現,點擊後會跳轉到一個 Login.jsp 頁面,這個不是我們想要的效果,我們需要自己定義一個Login頁面!
7. 我們編寫一個自己的Login頁面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登錄</title>
</head>
<body>
<form action="">
username <input type="text" name="username">
password <input type="password" name="password">
<input type="submit" value="提交">
</form>
</body>
</html>
8、編寫跳轉到 login 的 controller
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(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";
}
}
9. 在shiro中配置一下! ShiroFilterFactoryBean() 方法下面
@Configuration
public class ShiroConfig {
// 創建 ShiroFilterFactoryBean (3)
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//設置安全管理器
bean.setSecurityManager(securityManager);
//添加 shiro 的內置過濾器
/*
anon: 無需認證就可以訪問
authc: 必須認證了才能訪問
user: 必須擁有 “記住我” 功能才能用
perms: 擁有對某個資源的權限才能訪問
role: 擁有某個角色權限才能訪問
*/
Map<String, String> filterMap = new LinkedHashMap<>();
//攔截
filterMap.put("/user/add", "authc");
filterMap.put("/user/update", "authc");
bean.setFilterChainDefinitionMap(filterMap);
//如果沒有權限 就跳轉到這個頁面
bean.setLoginUrl("/toLogin");
return bean;
}
// 創建 DafaultWebSecurityManager (2)
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 關聯 Realm
securityManager.setRealm(userRealm);
return securityManager;
}
// 創建 realm 對象,需要自定義 (1)
@Bean()
public UserRealm userRealm() {
return new UserRealm();
}
}
10、再次測試,成功的跳轉到了我們指定的Login頁面!
11、優化一下代碼,我們這裏的攔截可以使用 通配符來操作
@Configuration
public class ShiroConfig {
// 創建 ShiroFilterFactoryBean (3)
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//設置安全管理器
bean.setSecurityManager(securityManager);
//添加 shiro 的內置過濾器
/*
anon: 無需認證就可以訪問
authc: 必須認證了才能訪問
user: 必須擁有 “記住我” 功能才能用
perms: 擁有對某個資源的權限才能訪問
role: 擁有某個角色權限才能訪問
*/
Map<String, String> filterMap = new LinkedHashMap<>();
//攔截
//filterMap.put("/user/add", "authc");
//filterMap.put("/user/update", "authc");
filterMap.put("/user/*", "authc");
bean.setFilterChainDefinitionMap(filterMap);
//如果沒有權限 就跳轉到這個頁面
bean.setLoginUrl("/toLogin");
return bean;
}
// 創建 DafaultWebSecurityManager (2)
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 關聯 Realm
securityManager.setRealm(userRealm);
return securityManager;
}
// 創建 realm 對象,需要自定義 (1)
@Bean()
public UserRealm userRealm() {
return new UserRealm();
}
}
12、測試,完全OK
登錄認證操作
1、編寫一個登錄的controller
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(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 token = new UsernamePasswordToken(username,password);
//執行登錄的方法,如果沒有異常說明 OK!
try{
subject.login(token);
return "index";
}catch (UnknownAccountException e){
//用戶不存在
model.addAttribute("msg","用戶名錯誤");
return "login";
}catch (IncorrectCredentialsException ice) {
//密碼錯誤
model.addAttribute("msg","密碼錯誤");
return "login";
}catch (Exception e){
return "login";
}
}
}
2、登錄頁面增加一個 msg 提示,並給表單增加一個提交地址:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登錄</title>
</head>
<body>
<p th:text="${msg}" style="color: red"></p>
<form th:action="@{/login}" method="post">
username <input type="text" name="username">
password <input type="password" name="password">
<input type="submit" value="提交">
</form>
</body>
</html>
3、理論,假設我們提交了表單,他會經過我們剛纔編寫的UserRealm
4、在 UserRealm 中編寫用戶認證的判斷邏輯
//執行認證邏輯
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("執行了=>認證邏輯AuthenticationToken");
//假設數據庫的用戶名和密碼
String name = "root";
String password = "123456";
//1.判斷用戶名
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
if (!userToken.getUsername().equals(name)) {
//用戶名不存在
return null; //shiro底層就會拋出 UnknownAccountException
}
//2. 驗證密碼,我們可以使用一個AuthenticationInfo實現類 SimpleAuthenticationInfo
// shiro會自動幫我們驗證!重點是第二個參數就是要驗證的密碼!
return new SimpleAuthenticationInfo("", password, "");
}
整合數據庫
1、導入Mybatis相關依賴( 準備工作已導入 )
2、編寫配置文件-連接配置 application.yml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/springbootdata?useUnicode=true&characterEncoding=utf-8&useSSL=true&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#druid 數據源專有配置
# 配置初始化大小、最小、最大
initialSize: 5
minIdle: 5
maxActive: 20
# 配置獲取連接等待超時的時間
maxWait: 60000
# 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連接,單位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一個連接在池中最小生存的時間,單位是毫秒
minEvictableIdleTimeMillis: 300000
# 如果validationQuery爲null,testOnBorrow、testOnReturn、testWhileIdle都不會起作用
validationQuery: SELECT 1 FROM DUAL
# 申請連接的時候檢測,如果空閒時間大於timeBetweenEvictionRunsMillis,執行validationQuery檢測連接是否有效。
testWhileIdle: true
# 申請 連接時執行validationQuery檢測連接是否有效,做了這個配置會降低性能
testOnBorrow: false
# 歸還 連接時執行validationQuery檢測連接是否有效,做了這個配置會降低性能
testOnReturn: false
# 打開PSCache,並且指定每個連接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置監控統計攔截的filters, 監控統計:"stat",防SQL注入:"wall",組合使用: "stat,wall"
filters: stat,wall,log4j
# 合併多個DruidDataSource的監控數據
useGlobalDataSourceStat: true
# 當建立新連接時被髮送給JDBC驅動的連接參數
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3、編寫mybatis的配置 application.properties
mybatis.type-aliases-package=com.jia.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
4、編寫實體類,引入Lombok
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data // 注在類上,提供類的get、set、equals、hashCode、canEqual、toString方法
@AllArgsConstructor // 注在類上,提供類的全參構造
@NoArgsConstructor // 注在類上,提供類的無參構造
public class User {
private int id;
private String name;
private String pwd;
private String perms;
}
5、編寫Mapper接口
@Repository
@Mapper
public interface UserMapper {
User queryUserByName(String name);
}
6、編寫Mapper配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jia.mapper.UserMapper">
<select id="queryUserByName" resultType="user" parameterType="String">
SELECT * from `user` where name = #{name}
</select>
</mapper>
7、編寫UserService 層
public interface UserService {
User queryUserByName(String name);
}
@Service
public class UserServiceimpl implements UserService{
@Autowired
UserMapper userMapper;
public User queryUserByName(String name){
return userMapper.queryUserByName(name);
}
}
8、改造UserRealm,連接到數據庫進行真實的操作!
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授權
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("授權--------------------------------------------------------------" + principals);
return null;
}
//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("認證--------------------------------------------------------------" + token);
//用戶名,密碼 (連接真實數據庫)
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
User user = userService.queryUserByName(userToken.getUsername());
//用戶名驗證
if (user == null) {
//沒有這個人 UnknownAccountException
return null;
}
//密碼驗證, shiro做
//可以加密: MD5加密 MD5鹽值加密
return new SimpleAuthenticationInfo(user, user.getPwd(), "");
}
}
思考:密碼比對原理探究
思考?這個Shiro,是怎麼幫我們實現密碼自動比對的呢?
我們可以去 realm 的父類 AuthorizingRealm 的父類 AuthenticatingRealm 中找一個方法 核心: getCredentialsMatcher() 翻譯過來:獲取證書匹配器
我們去看這個接口 CredentialsMatcher 有很多的實現類,MD5鹽值加密
我們的密碼一般都不能使用明文保存?需要加密處理;思路分析
- 如何把一個字符串加密爲MD5
- 替換當前的Realm 的 CredentialsMatcher 屬性,直接使用 Md5CredentialsMatcher 對象, 並設置加密算法
用戶授權操作
使用shiro的過濾器來攔截請求即可!
1、在 ShiroFilterFactoryBean 中添加一個過濾器
// 授權過濾器
filterMap.put("/user/add","perms[user:add]");
2、我們再次啓動測試一下,訪問add,發現以下錯誤!未授權錯誤!
3. 注意:當我們實現權限攔截後,shiro會自動跳轉到未授權的頁面,但我們沒有這個頁面,所有401 了
4. 配置一個未授權的提示的頁面,增加一個 controller 提示
@RequestMapping("/noauth")
public String unauthorized(){
return "user/noauth";
}
然後再 shiroFilterFactoryBean 中配置一個未授權的請求頁面!
//設置未授權頁面
bean.setUnauthorizedUrl("/noauth");
5. 測試,現在沒有授權,可以跳轉到我們指定的位置了!
Shiro授權
在UserRealm 中添加授權的邏輯,增加授權的字符串!
//授權
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("授權--------------------------------------------------------------" + principals);
// 給資源進行授權
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 添加資源的授權字符串
info.addStringPermission("user:add");
return info;
}
我們再次登錄測試,發現登錄的用戶是可以進行訪問add 頁面了!授權成功!
問題,我們現在完全是硬編碼,無論是誰登錄上來,都可以實現授權通過,但是真實的業務情況應該是,每個用戶擁有自己的一些權限,從而進行操作,所以說權限應該在用戶的數據庫中,正常的情況下,應該數據庫中是由一個權限表的,我們需要聯表查詢,但是這裏爲了大家操作理解方便一些,我們直接在數據庫表中增加一個字段來進行操作!
1、我們現在需要再自定義的授權認證中,獲取登錄的用戶,從而實現動態認證授權操作!
在用戶登錄授權的時候,將用戶放在 Principal 中,改造下之前的代碼
return new SimpleAuthenticationInfo(user, user.getPwd(), "");
2、然後再授權的地方獲得這個用戶,從而獲得它的權限
//授權
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("授權--------------------------------------------------------------" + principals);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//拿到當前用戶的對象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal(); //拿到User對象
//設置當前用戶的權限
info.addStringPermission(currentUser.getPerms());
return info;
}
3、我們給數據庫中的用戶增加一些權限
4、在過濾器中,將 update 請求也進行權限攔截下
//授權
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
5、我們啓動項目,登錄不同的賬戶,進行測試一下!
6、測試完美通過OK!
整合Thymeleaf
根據權限展示不同的前端頁面
1、添加Maven的依賴;
<!-- shiro-thymeleaf -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
2、配置一個shiro的Dialect ,在shiro的配置中增加一個Bean
//整合 ShiroDialect:用來整合 shiro thymeleaf
@Bean()
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
3、修改前端的配置
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}">update</a>
</div>
4、我們在去測試一下,可以發現,現在首頁什麼都沒有了,因爲我們沒有登錄,我們可以嘗試登錄下 ,來判斷這個Shiro的效果!登錄後,可以看到不同的用戶,有不同的效果,現在就已經接近完美 了~
5、爲了完美,我們在用戶登錄後應該把信息放到Session中,我們完善下!在執行認證邏輯時候,加 入session
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser", user);
6. 前端從session中獲取,然後用來判斷是否顯示登錄
<!--從 session 中判斷值-->
<div th:if="${session.loginUser == null}">
<a th:href="@{toLogin}">登錄</a>
</div>
Shiro MD5 登錄註冊
創建自定義 Realm 對象和密碼匹配憑證管理器
// 創建自定義 Realm 對象
@Bean(name = "UserRealm")
public UserRealm userRealm(@Qualifier("hashedCredentialsMatcher") HashedCredentialsMatcher matcher) {
UserRealm userRealm = new UserRealm();
userRealm.setCredentialsMatcher(matcher);
return userRealm;
}
// 密碼匹配憑證管理器
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
credentialsMatcher.setHashAlgorithmName("MD5"); //加密方式爲MD5
credentialsMatcher.setHashIterations(1024); //加密次數爲3次
credentialsMatcher.setStoredCredentialsHexEncoded(true);//採用hash散列算法加密
return credentialsMatcher;
}
new SimpleHash("MD5",user.getPassword(), user.getUsername(),1024).toHex();
第一項是加密方式,默認是MD5加密,第二項是需要加密的密碼,第三項是鹽值,一般使用用戶名,第四項是加密次數,這裏的次數必須和ShiroConfig中的加密方式的加密次數相同,否則密碼會匹配不成功。
註冊
@Test
void shiroContextLoads() {
MyUser user = new MyUser();
user.setName("qwe");
String md5 = new SimpleHash("MD5", ByteSource.Util.bytes("123123"), user.getName(), 1024).toHex();
user.setPwd(md5);
System.out.println(userServiceimpl.add(user));
}
登錄
本來如果兩個密碼是相同的那麼產生的MD5密碼也是一樣的,爲了使兩個密碼相同的時候所產生的密碼還不一樣進一步提高安全性,所以考慮添加鹽值。使用以下進行添加鹽值:
ByteSource credentialsSalt = ByteSource.Util.bytes(username);
//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("認證--------------------------------------------------------------" + token);
//用戶名,密碼 (連接真實數據庫)
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
MyUser user = userService.queryUserByName(userToken.getUsername());
//用戶名驗證
if (user == null) {
//沒有這個人 UnknownAccountException
return null;
}
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser", user);
//密碼驗證, shiro做
//可以加密: MD5加密 MD5鹽值加密
ByteSource salt = ByteSource.Util.bytes(user.getName());
return new SimpleAuthenticationInfo(user, user.getPwd(),salt, getName());
}