最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Spring Boot 集成Shiro和CAS

 更新時間:2017年05月17日 16:23:45   作者:catoop  
這篇文章主要介紹了詳解Spring Boot 集成Shiro和CAS,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

請大家在看本文之前,先了解如下知識點:

1、Shiro 是什么?怎么用?

2、Cas 是什么?怎么用?

3、最好有spring基礎(chǔ)

首先看一下下面這張圖:

第一個流程是單純使用Shiro的流程。

第二個流程是單純使用Cas的流程。

第三個圖是Shiro集成Cas后的流程。

PS:流程圖急急忙忙畫的,整體上應(yīng)該沒有什么問題,具體細(xì)節(jié)問題還請大家留言指正。

如果你只是打算用到你的Spring Boot項目中,那么看著如下配置完成便可。

如果你想進一步了解其中的細(xì)節(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";
  // 當(dāng)前工程對外提供的服務(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)/認(rè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);// 我們選擇認(rèn)證失敗后再打開登錄頁面
    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è)置默認(rèn)會自動尋找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)限認(rè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)限認(rèn)證,為當(dāng)前登錄的Subject授予角色和權(quán)限 
   * @see 經(jīng)測試:本例中該方法的調(diào)用時機為需授權(quán)資源被訪問時 
   * @see 經(jīng)測試:并且每次訪問需授權(quán)資源時都會執(zhí)行該方法中的邏輯,這表明本例中默認(rèn)并未啟用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)限認(rèn)證##################");
    //獲取當(dāng)前登錄輸入的用戶名,等價于(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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • SpringBoot配置文件中敏感信息加密的三種方法

    SpringBoot配置文件中敏感信息加密的三種方法

    當(dāng)我們將項目部署到服務(wù)器上時,一般會在jar包的同級目錄下加上application.yml配置文件,這樣可以在不重新?lián)Q包的情況下修改配置,這種方式存在安全隱患,如果配置文件泄露,就會造成數(shù)據(jù)庫密碼泄露,所以本文給大家介紹了SpringBoot配置文件中敏感信息加密的三種方法
    2024-05-05
  • Java自旋鎖的實現(xiàn)示例

    Java自旋鎖的實現(xiàn)示例

    自旋鎖是一種特殊的鎖,用于解決多線程同步問題,本文主要介紹了Java自旋鎖的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下
    2024-02-02
  • 解決RestTemplate 請求url中包含百分號 會被轉(zhuǎn)義成25的問題

    解決RestTemplate 請求url中包含百分號 會被轉(zhuǎn)義成25的問題

    這篇文章主要介紹了解決RestTemplate 請求url中包含百分號 會被轉(zhuǎn)義成25的問題,具有很好的參考價值,希望對大家有所幫助。
    2021-10-10
  • Response.AddHeader案例講解

    Response.AddHeader案例講解

    這篇文章主要介紹了Response.AddHeader案例講解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • springboot+mybatis報錯找不到實體類的問題

    springboot+mybatis報錯找不到實體類的問題

    這篇文章主要介紹了springboot+mybatis報錯找不到實體類的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • 逆波蘭計算器(Java實現(xiàn))

    逆波蘭計算器(Java實現(xiàn))

    這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)逆波蘭計算器,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-09-09
  • Java SQL注入案例教程及html基礎(chǔ)入門

    Java SQL注入案例教程及html基礎(chǔ)入門

    這篇文章主要介紹了前端開發(fā)每天必學(xué)之SQL及HTML入門基礎(chǔ)知識,介紹了學(xué)習(xí)web前端開發(fā)需要掌握的基礎(chǔ)技術(shù),感興趣的小伙伴們可以參考一下
    2021-07-07
  • java時間格式的簡單整理

    java時間格式的簡單整理

    這篇文章主要介紹了java時間格式的簡單整理,文中通過示例介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考一下
    2019-06-06
  • SpringBoot Knife4j在線API文檔框架基本使用

    SpringBoot Knife4j在線API文檔框架基本使用

    knife4j是為Java MVC框架集成Swagger生成Api文檔的增強解決方案,這篇文章主要介紹了SpringBoot中使用Knife4J在線API文檔框架,需要的朋友可以參考下
    2022-12-12
  • Spring?Boot中@Import三種使用方式實例詳解

    Spring?Boot中@Import三種使用方式實例詳解

    這篇文章主要介紹了Spring?Boot中@Import三種使用方式,主要有引入普通類,引入importSelector的實現(xiàn)類及引入importBeanDefinitionRegister的實現(xiàn)類,結(jié)合實例代碼給大家講解的非常詳細(xì),需要的朋友可以參考下
    2022-11-11

最新評論

平定县| 宝清县| 沂水县| 阿荣旗| 包头市| 万州区| 象州县| 家居| 禹州市| 贵南县| 左云县| 阿坝县| 唐山市| 济阳县| 清镇市| 英德市| 宜兰县| 林口县| 淮北市| 翁牛特旗| 兴文县| 宜宾市| 涞水县| 呼伦贝尔市| 河北省| 平利县| 延安市| 新巴尔虎左旗| 拉萨市| 团风县| 新闻| 宁乡县| 疏勒县| 巫山县| 潼关县| 天水市| 宁城县| 溧水县| 连平县| 大冶市| 台东县|