一、什麼是Filter
Filter在第一節中並未被提及,但是在shiro權限管理中有着極爲重要的作用,它主要負責配置泛的接口的權限,比如登錄,登出,這些肯定不會加權限驗證的和靜態資源訪問路徑等,也可以使用/**來配置全局的攔截路徑,只有在此filter中的接口,或者地址,纔會被shiro捕獲,進行權限控制。
二、引入依賴 pom.xml
首先是pom.xml配置,本文采用
- springboot2.0.4
- shiro-spring1.4.0
如果僅僅是使用shiro整合springboot,僅需要兩個jar即可。
<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>cn.junengxiong</groupId>
<artifactId>springboot-shiro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<!-- Web特性支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<!-- 熱部署模塊 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
</dependencies>
</project>
三、建立Filter
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 攔截器
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
// 配置不會被攔截的鏈接 順序判斷
filterChainDefinitionMap.put("/static/**", "anon");
filterChainDefinitionMap.put("/login", "anon");
// 配置退出 過濾器,其中具體的退出代碼Shiro已經替我們實現了
filterChainDefinitionMap.put("/logout", "logout");
// 過濾鏈定義,從上向下順序執行,一般將'/**'放在最爲下邊 因爲保存在LinkedHashMap中,順序很重要
// <!-- authc:所有url都必須認證通過纔可以訪問; anon:所有url都都可以匿名訪問-->
filterChainDefinitionMap.put("/**", "authc");//設置/** 爲user後,記住我纔會生效
// 如果不設置默認會自動尋找Web工程根目錄下的"/login.jsp"頁面,前後端分離設置此爲controller返回的未登錄的接口
// --------------------------------------------------
// 前後端分離使用下面設置
//shiroFilterFactoryBean.setLoginUrl("/login.html");
shiroFilterFactoryBean.setLoginUrl("/unauthorized");
// ---------------------------------------------------
// 登錄成功後跳轉的鏈接,前後端分離不用設置
// shiroFilterFactoryBean.setSuccessUrl("/index");
// 未授權的界面
shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
}
權限屬性
攔截器權限屬性 | 解釋 |
---|---|
anon | 可以匿名訪問 |
authc | 必須認證通過纔可以訪問 |
user | 記住我時可以訪問,配合rememberMe屬性 |