詳解Spring Boot 集成Shiro和CAS
請大家在看本文之前,先了解如下知識點:
1、Shiro 是什么?怎么用?
2、Cas 是什么?怎么用?
3、最好有spring基礎(chǔ)
首先看一下下面這張圖:
第一個流程是單純使用Shiro的流程。
第二個流程是單純使用Cas的流程。
第三個圖是Shiro集成Cas后的流程。

PS:流程圖急急忙忙畫的,整體上應(yīng)該沒有什么問題,具體細節(jié)問題還請大家留言指正。
如果你只是打算用到你的Spring Boot項目中,那么看著如下配置完成便可。
如果你想進一步了解其中的細節(jié),還是建議大家單獨配置Shiro、單獨配置Cas,看看官方相關(guān)文檔。
Shiro在1.2版本開始提供了對cas的集成,按下面添加依賴到pom.xml中:
<!--Apache Shiro所需的jar包 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-cas</artifactId>
<version>1.2.4</version>
</dependency>
shiro-cas 依賴 shiro-web,shiro-web 依賴 shiro-core,所以添加shiro-cas后shiro-web.jar和shiro-core.jar會自動被引用。
cas被shiro集成后,其原理就是shiro將casFilter加入到shiroFilter的filterChain中。
在SpringBoot工程中創(chuàng)建ShiroCasConfiguration.Java
package org.springboot.sample.config;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.Filter;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.cas.CasFilter;
import org.apache.shiro.cas.CasSubjectFactory;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springboot.sample.dao.IScoreDao;
import org.springboot.sample.security.MyShiroCasRealm;
import org.springboot.sample.service.StudentService;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;
/**
* Shiro集成Cas配置
*
* @author 單紅宇(365384722)
* @create 2016年1月17日
*/
@Configuration
public class ShiroCasConfiguration {
private static final Logger logger = LoggerFactory.getLogger(ShiroCasConfiguration.class);
// CasServerUrlPrefix
public static final String casServerUrlPrefix = "https://localhost:8443/cas";
// Cas登錄頁面地址
public static final String casLoginUrl = casServerUrlPrefix + "/login";
// Cas登出頁面地址
public static final String casLogoutUrl = casServerUrlPrefix + "/logout";
// 當前工程對外提供的服務(wù)地址
public static final String shiroServerUrlPrefix = "http://localhost:9090/myspringboot";
// casFilter UrlPattern
public static final String casFilterUrlPattern = "/shiro-cas";
// 登錄地址
public static final String loginUrl = casLoginUrl + "?service=" + shiroServerUrlPrefix + casFilterUrlPattern;
@Bean
public EhCacheManager getEhCacheManager() {
EhCacheManager em = new EhCacheManager();
em.setCacheManagerConfigFile("classpath:ehcache-shiro.xml");
return em;
}
@Bean(name = "myShiroCasRealm")
public MyShiroCasRealm myShiroCasRealm(EhCacheManager cacheManager) {
MyShiroCasRealm realm = new MyShiroCasRealm();
realm.setCacheManager(cacheManager);
return realm;
}
/**
* 注冊DelegatingFilterProxy(Shiro)
*
* @param dispatcherServlet
* @return
* @author SHANHY
* @create 2016年1月13日
*/
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
// 該值缺省為false,表示生命周期由SpringApplicationContext管理,設(shè)置為true則表示由ServletContainer管理
filterRegistration.addInitParameter("targetFilterLifecycle", "true");
filterRegistration.setEnabled(true);
filterRegistration.addUrlPatterns("/*");
return filterRegistration;
}
@Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator();
daap.setProxyTargetClass(true);
return daap;
}
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(MyShiroCasRealm myShiroCasRealm) {
DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
dwsm.setRealm(myShiroCasRealm);
// <!-- 用戶授權(quán)/認證信息Cache, 采用EhCache 緩存 -->
dwsm.setCacheManager(getEhCacheManager());
// 指定 SubjectFactory
dwsm.setSubjectFactory(new CasSubjectFactory());
return dwsm;
}
@Bean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
aasa.setSecurityManager(securityManager);
return aasa;
}
/**
* 加載shiroFilter權(quán)限控制規(guī)則(從數(shù)據(jù)庫讀取然后配置)
*
* @author SHANHY
* @create 2016年1月14日
*/
private void loadShiroFilterChain(ShiroFilterFactoryBean shiroFilterFactoryBean, StudentService stuService, IScoreDao scoreDao){
/////////////////////// 下面這些規(guī)則配置最好配置到配置文件中 ///////////////////////
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
filterChainDefinitionMap.put(casFilterUrlPattern, "casFilter");// shiro集成cas后,首先添加該規(guī)則
// authc:該過濾器下的頁面必須驗證后才能訪問,它是Shiro內(nèi)置的一個攔截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter
filterChainDefinitionMap.put("/user", "authc");// 這里為了測試,只限制/user,實際開發(fā)中請修改為具體攔截的請求規(guī)則
// anon:它對應(yīng)的過濾器里面是空的,什么都沒做
logger.info("##################從數(shù)據(jù)庫讀取權(quán)限規(guī)則,加載到shiroFilter中##################");
filterChainDefinitionMap.put("/user/edit/**", "authc,perms[user:edit]");// 這里為了測試,固定寫死的值,也可以從數(shù)據(jù)庫或其他配置中讀取
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/**", "anon");//anon 可以理解為不攔截
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
}
/**
* CAS過濾器
*
* @return
* @author SHANHY
* @create 2016年1月17日
*/
@Bean(name = "casFilter")
public CasFilter getCasFilter() {
CasFilter casFilter = new CasFilter();
casFilter.setName("casFilter");
casFilter.setEnabled(true);
// 登錄失敗后跳轉(zhuǎn)的URL,也就是 Shiro 執(zhí)行 CasRealm 的 doGetAuthenticationInfo 方法向CasServer驗證tiket
casFilter.setFailureUrl(loginUrl);// 我們選擇認證失敗后再打開登錄頁面
return casFilter;
}
/**
* ShiroFilter<br/>
* 注意這里參數(shù)中的 StudentService 和 IScoreDao 只是一個例子,因為我們在這里可以用這樣的方式獲取到相關(guān)訪問數(shù)據(jù)庫的對象,
* 然后讀取數(shù)據(jù)庫相關(guān)配置,配置到 shiroFilterFactoryBean 的訪問規(guī)則中。實際項目中,請使用自己的Service來處理業(yè)務(wù)邏輯。
*
* @param myShiroCasRealm
* @param stuService
* @param scoreDao
* @return
* @author SHANHY
* @create 2016年1月14日
*/
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager, CasFilter casFilter, StudentService stuService, IScoreDao scoreDao) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 必須設(shè)置 SecurityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 如果不設(shè)置默認會自動尋找Web工程根目錄下的"/login.jsp"頁面
shiroFilterFactoryBean.setLoginUrl(loginUrl);
// 登錄成功后要跳轉(zhuǎn)的連接
shiroFilterFactoryBean.setSuccessUrl("/user");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
// 添加casFilter到shiroFilter中
Map<String, Filter> filters = new HashMap<>();
filters.put("casFilter", casFilter);
shiroFilterFactoryBean.setFilters(filters);
loadShiroFilterChain(shiroFilterFactoryBean, stuService, scoreDao);
return shiroFilterFactoryBean;
}
}
創(chuàng)建權(quán)限認證的 MyShiroCasRealm.java
package org.springboot.sample.security;
import java.util.List;
import javax.annotation.PostConstruct;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springboot.sample.config.ShiroCasConfiguration;
import org.springboot.sample.dao.IUserDao;
import org.springboot.sample.entity.Role;
import org.springboot.sample.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
public class MyShiroCasRealm extends CasRealm{
private static final Logger logger = LoggerFactory.getLogger(MyShiroCasRealm.class);
@Autowired
private IUserDao userDao;
@PostConstruct
public void initProperty(){
// setDefaultRoles("ROLE_USER");
setCasServerUrlPrefix(ShiroCasConfiguration.casServerUrlPrefix);
// 客戶端回調(diào)地址
setCasService(ShiroCasConfiguration.shiroServerUrlPrefix + ShiroCasConfiguration.casFilterUrlPattern);
}
/**
* 權(quán)限認證,為當前登錄的Subject授予角色和權(quán)限
* @see 經(jīng)測試:本例中該方法的調(diào)用時機為需授權(quán)資源被訪問時
* @see 經(jīng)測試:并且每次訪問需授權(quán)資源時都會執(zhí)行該方法中的邏輯,這表明本例中默認并未啟用AuthorizationCache
* @see 經(jīng)測試:如果連續(xù)訪問同一個URL(比如刷新),該方法不會被重復(fù)調(diào)用,Shiro有一個時間間隔(也就是cache時間,在ehcache-shiro.xml中配置),超過這個時間間隔再刷新頁面,該方法會被執(zhí)行
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
logger.info("##################執(zhí)行Shiro權(quán)限認證##################");
//獲取當前登錄輸入的用戶名,等價于(String) principalCollection.fromRealm(getName()).iterator().next();
String loginName = (String)super.getAvailablePrincipal(principalCollection);
//到數(shù)據(jù)庫查是否有此對象
User user=userDao.findByName(loginName);// 實際項目中,這里可以根據(jù)實際情況做緩存,如果不做,Shiro自己也是有時間間隔機制,2分鐘內(nèi)不會重復(fù)執(zhí)行該方法
if(user!=null){
//權(quán)限信息對象info,用來存放查出的用戶的所有的角色(role)及權(quán)限(permission)
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
//用戶的角色集合
info.setRoles(user.getRolesName());
//用戶的角色對應(yīng)的所有權(quán)限,如果只使用角色定義訪問權(quán)限,下面的四行可以不要
List<Role> roleList=user.getRoleList();
for (Role role : roleList) {
info.addStringPermissions(role.getPermissionsName());
}
// 或者按下面這樣添加
//添加一個角色,不是配置意義上的添加,而是證明該用戶擁有admin角色
// simpleAuthorInfo.addRole("admin");
//添加權(quán)限
// simpleAuthorInfo.addStringPermission("admin:manage");
// logger.info("已為用戶[mike]賦予了[admin]角色和[admin:manage]權(quán)限");
return info;
}
// 返回null的話,就會導(dǎo)致任何用戶訪問被攔截的請求時,都會自動跳轉(zhuǎn)到unauthorizedUrl指定的地址
return null;
}
}
在Controller中添加一個方法,用于將登錄URL簡單化,提供一個重定向功能
@RequestMapping(value="/login",method=RequestMethod.GET)
public String loginForm(Model model){
model.addAttribute("user", new User());
// return "login";
return "redirect:" + ShiroCasConfiguration.loginUrl;
}
本文主要是介紹如何在Spring Boot中集成Shiro+Cas,并非一個從零創(chuàng)建工程到整體完成的介紹。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- spring boot 1.5.4 集成shiro+cas,實現(xiàn)單點登錄和權(quán)限控制
- SpringBoot集成Shiro進行權(quán)限控制和管理的示例
- springmvc集成shiro登錄權(quán)限示例代碼
- spring boot集成shiro詳細教程(小結(jié))
- spring boot 集成shiro的配置方法
- Spring Boot集成Shiro并利用MongoDB做Session存儲的方法詳解
- 詳解spring與shiro集成
- shiro無狀態(tài)web集成的示例代碼
- Spring 應(yīng)用中集成 Apache Shiro的方法
- Shiro集成Spring之注解示例詳解
相關(guān)文章
JAVA實戰(zhàn)練習之圖書管理系統(tǒng)實現(xiàn)流程
隨著網(wǎng)絡(luò)技術(shù)的高速發(fā)展,計算機應(yīng)用的普及,利用計算機對圖書館的日常工作進行管理勢在必行,本篇文章手把手帶你用Java實現(xiàn)一個圖書管理系統(tǒng),大家可以在過程中查缺補漏,提升水平2021-10-10
Java?Mybatis?foreach嵌套foreach?List<list<Object>&
在MyBatis的mapper.xml文件中,foreach元素常用于動態(tài)生成SQL查詢條件,此元素包括item(必選,元素別名)、index(可選,元素序號或鍵)、collection(必選,指定迭代對象)、open、separator、close(均為可選,用于定義SQL結(jié)構(gòu))2024-09-09
Mybatis-plus自動填充不生效或自動填充數(shù)據(jù)為null原因及解決方案
本文主要介紹了Mybatis-plus自動填充不生效或自動填充數(shù)據(jù)為null原因及解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-05-05
淺談SpringCloud實現(xiàn)簡單的微服務(wù)架構(gòu)
Spring Cloud是一系列框架的有序集合,本文就使用SpringCloud實現(xiàn)一套簡單的微服務(wù)架構(gòu),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01
SpringBoot集成ip2region實現(xiàn)ip白名單的代碼示例
ip2region v2.0 - 是一個離線IP地址定位庫和IP定位數(shù)據(jù)管理框架,10微秒級別的查詢效率,提供了眾多主流編程語言的 xdb 數(shù)據(jù)生成和查詢客戶端實現(xiàn),本文介紹了SpringBoot集成ip2region實現(xiàn)ip白名單的代碼工程,需要的朋友可以參考下2024-08-08
詳解 Corba開發(fā)之Java實現(xiàn)Service與Client
這篇文章主要介紹了詳解 Corba開發(fā)之Java實現(xiàn)Service與Client的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下2017-10-10
SpringBoot整合WebSocket實現(xiàn)后端向前端主動推送消息方式
這篇文章主要介紹了SpringBoot整合WebSocket實現(xiàn)后端向前端主動推送消息方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10

