Shiro簡介
1.Apache Shiro 是一個Java 的安全(權限)框架。
2.Shiro 可以非常容易的開發出足夠好的應用,其不僅可以用在JavaSE環境,也可以用在JavaEE環
境。
3.Shiro可以完成,認證,授權,加密,會話管理,Web集成,緩存等。
4.下載地址:http://shiro.apache.org/
有哪些功能
Authentication:身份認證、登錄,驗證用戶是不是擁有相應的身份;
Authorization:授權,即權限驗證,驗證某個已認證的用戶是否擁有某個權限,即判斷用戶能否
進行什么操作,如:驗證某個用戶是否擁有某個角色,或者細粒度的驗證某個用戶對某個資源是否具有某個權限!
Session Manager:會話管理,即用戶登錄后就是第一次會話,在沒有退出之前,它的所有信息都
在會話中;會話可以是普通的JavaSE環境,也可以是Web環境;
Cryptography:加密,保護數據的安全性,如密碼加密存儲到數據庫中,而不是明文存儲;
Web Support:Web支持,可以非常容易的集成到Web環境;
Caching:緩存,比如用戶登錄后,其用戶信息,擁有的角色、權限不必每次去查,這樣可以提高
效率
Concurrency:Shiro支持多線程應用的並發驗證,即,如在一個線程中開啟另一個線程,能把權限
自動的傳播過去
Testing:提供測試支持;
Run As:允許一個用戶假裝為另一個用戶(如果他們允許)的身份進行訪問;
Remember Me:記住我,這個是非常常見的功能,即一次登錄后,下次再來的話不用登錄了
Shiro架構(外部)
從外部來看Shiro,即從應用程序角度來觀察如何使用shiro完成工作:
1.subject: 應用代碼直接交互的對象是Subject,也就是說Shiro的對外API核心就是Subject,
Subject代表了當前的用戶,這個用戶不一定是一個具體的人,與當前應用交互的任何東西都是
Subject,如網絡爬蟲,機器人等,與Subject的所有交互都會委托給SecurityManager;Subject其
實是一個門面,SecurityManageer 才是實際的執行者
2.SecurityManager:安全管理器,即所有與安全有關的操作都會與SercurityManager交互,並且它
管理着所有的Subject,可以看出它是Shiro的核心,它負責與Shiro的其他組件進行交互,它相當於
SpringMVC的DispatcherServlet的角色
3.Realm:Shiro從Realm獲取安全數據(如用戶,角色,權限),就是說SecurityManager 要驗證
用戶身份,那么它需要從Realm 獲取相應的用戶進行比較,來確定用戶的身份是否合法;也需要從
Realm得到用戶相應的角色、權限,進行驗證用戶的操作是否能夠進行,可以把Realm看成
DataSource;
Shiro架構(內部)
1.Subject:任何可以與應用交互的 ‘用戶’;
2.Security Manager:相當於SpringMVC中的DispatcherServlet;是Shiro的心臟,所有具體的交互
都通過Security Manager進行控制,它管理者所有的Subject,且負責進行認證,授權,會話,及
緩存的管理。
3.Authenticator:負責Subject認證,是一個擴展點,可以自定義實現;可以使用認證策略
(Authentication Strategy),即什么情況下算用戶認證通過了;
4.Authorizer:授權器,即訪問控制器,用來決定主體是否有權限進行相應的操作;即控制着用戶能
訪問應用中的那些功能;
5.Realm:可以有一個或者多個的realm,可以認為是安全實體數據源,即用於獲取安全實體的,可
以用JDBC實現,也可以是內存實現等等,由用戶提供;所以一般在應用中都需要實現自己的realm
SessionManager:管理Session生命周期的組件,而Shiro並不僅僅可以用在Web環境,也可以用
在普通的JavaSE環境中
6.CacheManager :緩存控制器,來管理如用戶,角色,權限等緩存的;因為這些數據基本上很少改
變,放到緩存中后可以提高訪問的性能;
7.Cryptography:密碼模塊,Shiro 提高了一些常見的加密組件用於密碼加密,解密等
快速實踐
查看官網文檔:http://shiro.apache.org/tutorial.html
官方的quickstart:https://github.com/apache/shiro/tree/master/samples/quickstart/
1.創建一個maven父工程,用於學習Shiro,刪掉不必要的東西
2.創建一個普通的Maven子工程:springboot-08-shiro
3.根據官方文檔,我們來導入Shiro的依賴
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.1</version>
</dependency>
<!-- configure logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
4.編寫Shiro配置
log4j.properties
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
[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();
SecurityUtils.setSecurityManager(securityManager);
// get the currently executing user:
//獲取當前的用戶對象
Subject currentUser = SecurityUtils.getSubject();
// 通過當前用戶拿到shiro的session(並不是http的Session)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Subject=>session[" + value + "]");
}
// 判斷當前的用戶是否被認證
if (!currentUser.isAuthenticated()) {
//Token: 令牌
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true); //設置記住我
try {
currentUser.login(token); //執行登錄操作~
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... catch 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.測試運行一下沒問題:
從這個例子看出,Shiro通過Subject對外提供API!
接下來我們在SpringBoot中集成Shiro!
SpringBoot集成Shiro
搭建環境
搭建一個SpringBoot項目、選中web模塊即可!
導入Maven依賴 thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
編寫一個頁面 index.html
<!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>
<hr>
<a th:href="@{/user/add}">add</a> | <a th:href="@{/user/update}">update</a>
</body>
</html>
編寫controller進行訪問測試
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","hello,Shiro");
return "index";
}
}
測試訪問首頁!
整合Shrio
回顧核心API:
-
Subject:用戶主體
-
SecurityManager:安全管理器
-
Realm:Shiro 連接數據
步驟:
導入Shiro 和 spring整合的依賴
<!--導入Shiro整合springboot的包-->
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.1</version>
</dependency>
編寫Shiro 配置類:
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean:3第三步
//DefaultWebSecurityManager:2第二步
//創建Realm對象,需要自定義:1第一步
}
我們倒着來,先想辦法創建一個 realm 對象
我們需要自定義一個 realm 的類,用來編寫一些查詢的方法,或者認證與授權的邏輯
//自定義的Realm
public class UserRealm extends AuthorizingRealm {
//授權
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("執行了=>授權doGetAuthorizationInfo");
return null;
}
//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("執行了=>認證doGetAuthenticationInfo");
return null;
}
}
將這個類在ShiroConfig 注冊到我們的spring容器中!
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean:3第三步
//DefaultWebSecurityManager:2第二步
//創建Realm對象,需要自定義:1第一步
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
}
接下來我們該去創建 DefaultWebSecurityManager 了
//DefaultWebSecurityManager:2第二步
@Bean(name="securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//關聯UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
接下來我們該去創建 ShiroFilterFactoryBean 了
//ShiroFilterFactoryBean:3第三步
@Bean(name = "shiroFilterFactoryBean")
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//設置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
return bean;
}
最后上完整的配置:
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean:3第三步
@Bean(name = "shiroFilterFactoryBean")
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//設置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
return bean;
}
//DefaultWebSecurityManager:2第二步
@Bean(name="securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//關聯UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//創建Realm對象,需要自定義:1第一步
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
}
頁面攔截實現
編寫兩個頁面、在templates目錄下新建一個 user 目錄 add.html update.html
<body>
<h1>add</h1>
</body>
<body>
<h1>update</h1>
</body>
編寫跳轉到頁面的controller
@RequestMapping("/user/add")
public String add(){
return "user/add";
}
@RequestMapping("/user/update")
public String update(){
return "user/update";
}
在index頁面上,增加跳轉鏈接
<a th:href="@{/user/add}">add</a> | <a th:href="@{/user/update}">update</a>
測試頁面跳轉是否OK
准備添加Shiro的內置過濾器
//ShiroFilterFactoryBean:3第三步
@Bean(name = "shiroFilterFactoryBean")
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//設置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//添加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;
}
再起啟動測試,訪問鏈接進行測試!攔截OK!但是發現,點擊后會跳轉到一個Login.jsp頁面,這
個不是我們想要的效果,我們需要自己定義一個Login頁面!
我們編寫一個自己的Login頁面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登錄</h1>
<hr>
<p th:text="${msg}" style="color:red;"></p>
<form th:action="@{/login}">
<p>用戶名: <input type="text" name="username"></p>
<p>密碼: <input type="text" name="password"></p>
<p><input type="submit"></p>
</form>
</body>
</html>
編寫跳轉的controller
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
在shiro中配置一下! ShiroFilterFactoryBean() 方法下面
//修改到要跳轉的login頁面;
shiroFilterFactoryBean.setLoginUrl("/toLogin");
再次測試,成功的跳轉到了我們指定的Login頁面!
優化一下代碼,我們這里的攔截可以使用 通配符來操作
Map<String, String> filterMap = new LinkedHashMap<>();
// filterMap.put("/user/add","authc");
// filterMap.put("/user/update","authc");
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
測試,完全OK!
登錄認證操作
編寫一個登錄的controller
@RequestMapping("/login")
public String login(String username,String password,Model model){
//獲取當前的用戶
Subject subject = SecurityUtils.getSubject();
//封裝用戶的登錄數據
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try{
subject.login(token); //執行登錄的方法,如果沒有異常就說明ok
return "index";
}catch (UnknownAccountException e){//用戶名不存在
model.addAttribute("msg","用戶名錯誤");
return "login";
}catch (IncorrectCredentialsException e){ //密碼不存在
model.addAttribute("msg","密碼錯誤");
return "login";
}
}
在前端修改對應的信息輸出或者請求!
login.html登錄頁面增加一個 msg 提示:
<p th:text="${msg}" style="color:red;"></p>
給表單增加一個提交地址:
<form th:action="@{/login}">
<p>用戶名: <input type="text" name="username"></p>
<p>密碼: <input type="text" name="password"></p>
<p><input type="submit"></p>
</form>
理論,假設我們提交了表單,他會經過我們剛才編寫的UserRealm,我們提交測試一下
確實執行了我們的認證邏輯!
在 UserRealm 中編寫用戶認證的判斷邏輯
//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("執行了=>認證doGetAuthenticationInfo");
//認證用戶名和密碼 數據庫中取
String name = "root";
String password = "123456";
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//用戶名認證
if(!userToken.getUsername().equals(name)){
return null ;//此時return null就會拋出異常 UnknownAccountException
}
// 驗證密碼,我們可以使用一個AuthenticationInfo實現類 SimpleAuthenticationInfo
//密碼認證,shiro幫你做,只需要像下面把正確的密碼丟進去
//shiro會自動幫我們驗證!重點是第二個參數就是要驗證的密碼!
return new SimpleAuthenticationInfo("",password,"");
}
測試一下!成功實現登錄的認證操作!
Shiro整合Mybatis
導入Mybatis相關依賴
<!--mysql驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--mybatis整合包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
編寫配置文件-連接配置 application.yml
spring:
datasource:
username: root
password: 123456
#?serverTimezone=UTC解決時區的報錯
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默認是不注入這些屬性值的,需要自己綁定
#druid 數據源專有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置監控統計攔截的filters,stat:監控統計、log4j:日志記錄、wall:防御sql注入
#如果允許時報錯 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#則導入 log4j 依賴即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
編寫mybatis的配置 application.properties
mybatis.type-aliases-package=com.kuang.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
編寫實體類,
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
編寫Mapper接口
@Repository
@Mapper
public interface UserMapper {
public User queryUserByName(String name);
}
編寫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.kuang.mapper.UserMapper">
<select id="queryUserByName" parameterType="String" resultType="User">
select * from user where name=#{name}
</select>
</mapper>
編寫UserService 層
public interface UserService {
public User queryUserByName(String name);
}
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public User queryUserByName(String name) {
return userMapper.queryUserByName(name);
}
}
好了,一口氣寫了這些常規操作,可以去測試一下了,保證能夠從數據庫中查詢出來
@SpringBootTest
class ShiroSpringbootApplicationTests {
@Autowired
UserServiceImpl userService;
@Test
void contextLoads() {
System.out.println(userService.queryUserByName("狂神"));
}
}
完全OK,成功查詢出來了!
改造UserRealm,連接到數據庫進行真實的操作!
//自定義的Realm
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授權
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("執行了=>授權doGetAuthorizationInfo");
return null;
}
//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("執行了=>認證doGetAuthenticationInfo");
//認證用戶名和密碼 數據庫中取
// String name = "root";
// String password = "123456";
//用戶名認證
// if(!userToken.getUsername().equals(name)){
// return null ;//此時return null就會拋出異常 UnknownAccountException
// }
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//連接真實數據庫
User user = userService.queryUserByName(userToken.getUsername());
if(user == null){
return null;
}
//密碼可以加密: MD5 MD5鹽值加密
//密碼認證,shiro幫你做,只需要像下面把正確的密碼丟進去
return new SimpleAuthenticationInfo("",user.getPwd(),"");
}
}
測試ok,現在查詢都是從數據庫查詢的了!
思考:密碼比對原理探究
思考?這個Shiro,是怎么幫我們實現密碼自動比對的呢?
我們可以去 realm的父類 AuthorizingRealm 的父類 AuthenticatingRealm 中找一個方法
核心: getCredentialsMatcher() 翻譯過來:獲取證書匹配器
我們去看這個接口 CredentialsMatcher 有很多的實現類,MD5鹽值加密
我們的密碼一般都不能使用明文保存?需要加密處理;思路分析
-
如何把一個字符串加密為MD5
-
替換當前的Realm 的 CredentialsMatcher 屬性,直接使用 Md5CredentialsMatcher 對象,
並設置加密算法
用戶授權操作
使用shiro的過濾器來攔截請求即可!
- 在 ShiroFilterFactoryBean 中添加一個過濾器
//授權攔截,正常的情況下,沒有授權會跳轉到未授權頁面 ,大家記得注意順序,這里授權攔截在認證攔截前面!
filterMap.put("/user/add","perms[user:add]");//他的意思是說,請求/user/add的時候,需要有user:add這種字符串的權限
filterMap.put("/user/update","perms[user:update]");
//認證攔截
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
我們再次啟動測試一下,訪問add,發現以下錯誤!未授權錯誤!
注意:當我們實現權限攔截后,shiro會自動跳轉到未授權的頁面,但我們沒有這個頁面,所有401
了
配置一個未授權的提示的頁面,增加一個controller提示
@RequestMapping("/noauth")
@ResponseBody
public String unauthorized(){
return "未經授權無法訪問此頁面";
}
然后在ShiroConfig.java中的shiroFilterFactoryBean 中配置一個未授權的請求頁面!
//設置未授權頁面的請求
bean.setUnauthorizedUrl("/noauth");
測試,現在沒有授權,可以跳轉到我們指定的位置了!
Shiro授權
在UserRealm 中添加授權的邏輯,增加授權的字符串!
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("執行了=>授權doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermission("user:add");
return info;
}
我們再次登錄測試,發現登錄的用戶是可以進行訪問add 頁面了!授權成功!
問題,我們現在完全是硬編碼,無論是誰登錄上來,都可以實現授權通過,但是真實的業務情況應該
是,每個用戶擁有自己的一些權限,從而進行操作,所以說,權限,應該在用戶的數據庫中,正常的情
況下,應該數據庫中是由一個權限表的,我們需要聯表查詢,但是這里為了大家操作理解方便一些,我
們直接在數據庫表中增加一個字段來進行操作!
修改實體類,增加一個字段
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
private String perms;
}
我們現在需要再自定義的授權認證中,獲取登錄的用戶,從而實現動態認證授權操作!
在用戶登錄授權的時候,在UserRealm.java的doGetAuthenticationInfo方法將用戶放在 Principal 中,改造下之前的代碼
//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
然后再授權的地方獲得這個用戶,從而獲得它的權限
//授權
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("執行了=>授權doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//info.addStringPermission("user:add");
//拿到當前登錄的這個對象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal(); //拿到user對象
//設置當前用戶的權限
info.addStringPermission(currentUser.getPerms());
return info;
}
我們給數據庫中的用戶增加一些權限
在過濾器中(也就是ShiroConfig.java中的getShiroFilterFactoryBean方法),將 update 請求也進行權限攔截下
//授權攔截,正常的情況下,沒有授權會跳轉到未授權頁面
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
我們啟動項目,登錄不同的賬戶,進行測試一下!
測試完美通過OK!
Shiro整合Thymeleaf
根據權限展示不同的前端頁面
添加Maven的依賴;
<!--Shiro與Thymeleaf整合的包-->
<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
配置一個shiro的Dialect ,在shiro的配置中增加一個Bean
//用來整合shiro和thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
修改前端index.html的配置
<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>
我們在去測試一下,可以發現,現在首頁什么都沒有了,因為我們沒有登錄,我們可以嘗試登錄下,來判斷這個Shiro的效果!登錄后,可以看到不同的用戶,有不同的效果,現在就已經接近完美了~!還不是最完美
為了完美,我們在用戶登錄后應該把信息放到Session(這個session不是httpSession而是shiro中的)中,我們完善下!我們在登錄成功后,加入session
@RequestMapping("/login")
public String login(String username,String password,Model model){
//獲取當前的用戶
Subject subject = SecurityUtils.getSubject();
//封裝用戶的登錄數據
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
User user = userService.queryUserByName(token.getUsername());
try{
subject.login(token); //執行登錄的方法,如果沒有異常就說明ok
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser",user);
return "index";
}catch (UnknownAccountException e){//用戶名不存在
model.addAttribute("msg","用戶名錯誤");
return "login";
}catch (IncorrectCredentialsException e){ //密碼不存在
model.addAttribute("msg","密碼錯誤");
return "login";
}
}
前端index.html從session(不是httpSession,而是shiro中的)中獲取,然后用來判斷是否顯示登錄
<div th:if="${session.loginUser==null}">
<a th:href="@{/toLogin}">登錄</a>
</div>
測試,效果完美!