4、cas4.2.x支持MySQL、shiro|8月更文挑戰

這是我參與8月更文挑戰的第8天,活動詳情查看:8月更文挑戰css

 能夠參照官方文檔弄:apereo.github.io/cas/4.2.x/i…html

首先將mysql驅動jar包導入項目的lib中,而後在tomcat裏找到cas的配置文件:deployerConfigContext.xml 、 cas.properties 進行配置。java

配置deployerConfigContext.xml

註釋掉:     mysql

<alias name="acceptUsersAuthenticationHandler" alias="primaryAuthenticationHandler" />
複製代碼

  增長數據庫鏈接池配置:特別注意的是:jdbcUrl的配置,裏面若是有「&」 的,要替換成「&」,不替換tomcat啓動的時候報錯:【對實體 "characterEncoding" 的引用必須以 ';' 分隔符結尾】,另外,jdbcUrl根據具體狀況配置,不是固定寫法。git

<bean id="dataSource"
      class="com.mchange.v2.c3p0.ComboPooledDataSource"
      p:driverClass="com.mysql.jdbc.Driver"
      p:jdbcUrl="jdbc:mysql://127.0.0.1:3306/renren?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull"
      p:user="root"
      p:password="root"
      p:initialPoolSize="6"
      p:minPoolSize="6"
      p:maxPoolSize="18"
      p:maxIdleTimeExcessConnections="120"
      p:checkoutTimeout="10000"
      p:acquireIncrement="6"
      p:acquireRetryAttempts="5"
      p:acquireRetryDelay="2000"
      p:idleConnectionTestPeriod="30"
      p:preferredTestQuery="select 1" />
複製代碼

能夠參照官網,把參數寫到cas.properties配置文件中github

 在deployerConfigContext.xml里加入:web

<alias name="queryDatabaseAuthenticationHandler" alias="primaryAuthenticationHandler" />
<alias name="dataSource" alias="queryDatabaseDataSource" />
複製代碼

      在cas.properties里加入:此文件中本來就有這行配置,是被註釋掉的,能夠放開,或者直接複製進去就行,【=】號後面的是查詢mysql的sql語句,根據用戶名查密碼。須要本身更改。spring

cas.jdbc.authn.query.sql=select password from users where username=?
複製代碼

      都保存了,重啓tomcat作實驗就行啦。sql

前面不是提到過 cas默認用戶是casuser嗎?他是在cas.properties中配置數據庫

cas4.2.x配置shiro

 在 cas client中配置shiro,參照了好多大神的作法

在客戶端pom.xml中引入shiro jar包

而後在web.xml中配置shiro filter

   <!-- Shiro Security filter -->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
       
    </filter-mapping>
複製代碼

關鍵點是在shiro.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="  
     http://www.springframework.org/schema/beans   
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
     http://www.springframework.org/schema/context   
     http://www.springframework.org/schema/context/spring-context-3.0.xsd  
     http://www.springframework.org/schema/util  
     http://www.springframework.org/schema/util/spring-util-3.0.xsd"
    default-lazy-init="true">
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager" />
        <!-- 設定角色的登陸連接,這裏爲cas登陸頁面的連接可配置回調地址 -->
        <property name="loginUrl"
            value="http://192.168.7.116:9000/cas/login?service=http://127.0.0.1:8081/BF/shiro-cas" />
        <property name="successUrl" value="/login"></property>
        <property name="filters">
            <util:map>
                <entry key="casFilter" value-ref="casFilter" />
                <entry key="logout" value-ref="logout" />
            </util:map>
        </property>
        <property name="filterChainDefinitions">
            <value>
                /shiro-cas* = casFilter
                /images/** = anon
                /css/** = anon
                /js/** = anon
                /static/** =anon
                /logout = logout
                /** =authc
            </value>
        </property>
    </bean>
    <!-- shiro-cas登陸過濾器 -->
    <bean id="casFilter" class="org.apache.shiro.cas.CasFilter">
        <!-- 配置驗證錯誤時的失敗頁面 ,這裏配置爲登陸頁面 -->
        <property name="failureUrl"
            value="http://192.168.7.116:9000/cas/login?service=http://127.0.0.1:8081/BF/shiro-cas" />
    </bean>
    <!-- 退出登陸過濾器 -->
    <bean id="logout" class="org.apache.shiro.web.filter.authc.LogoutFilter">
        <property name="redirectUrl"
            value="http://192.168.7.116:9000/cas/logout?service=http://127.0.0.1:8081/BF/shiro-cas" />
    </bean>

    <!-- 自定義casRealm -->
    <bean id="casRealm" class="com.fca.shiro.MyCasRealm">
        <!-- <property name="defaultRoles" value="ROLE_USER" /> -->
        <!-- 配置cas服務器地址 -->
        <property name="casServerUrlPrefix" value="http://192.168.7.116:9000/cas" />
        <!-- 客戶端的回調地址設置,必須和上面的shiro-cas過濾器casFilter攔截的地址一致 -->
        <property name="casService" value="http://127.0.0.1:8081/BF/shiro-cas" />
    </bean>

    <!--緩存機制 -->
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache.xml" />
    </bean>

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="casRealm" />
        <property name="subjectFactory" ref="casSubjectFactory" />
        <property name="cacheManager" ref="cacheManager" />
    </bean>

    <!-- 若是要實現cas的remember me的功能,須要用到下面這個bean,並設置到securityManager的subjectFactory中 -->
    <bean id="casSubjectFactory" class="org.apache.shiro.cas.CasSubjectFactory" />

    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

    <bean
        class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="staticMethod"
            value="org.apache.shiro.SecurityUtils.setSecurityManager" />
        <property name="arguments" ref="securityManager" />
    </bean>
</beans>

複製代碼

這裏我把ehcache.xml也貼出來,方便粘貼

<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="shirocache">

    <diskStore path="java.io.tmpdir"/>

     <defaultCache
        maxElementsInMemory="2000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />
        
<!--     <cache name="diskCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache> -->
    
    <cache name="passwordRetryCache"
           maxElementsInMemory="2000"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           >
    </cache>

    <cache name="authorizationCache"
           maxElementsInMemory="2000"
           eternal="false"
           timeToIdleSeconds="1800"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           >
    </cache>

    <cache name="authenticationCache"
           maxElementsInMemory="2000"
           eternal="false"
           timeToIdleSeconds="1800"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           >
    </cache>

    <cache name="shiro-activeSessionCache"
           maxElementsInMemory="2000"
           eternal="false"
           timeToIdleSeconds="1800"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           >
    </cache>
</ehcache>

複製代碼

最後就是自定義的MyCasRealm類了,

package com.fca.shiro;

import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class MyCasRealm extends CasRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal(); // 從這裏能夠從cas server得到認證經過的用戶名,獲得後咱們能夠根據用戶名進行具體的受權
        // 也能夠從 Subject subject = SecurityUtils.getSubject();
        // return (String)subject.getPrincipals().asList().get(0); 中取得,由於已經整合後 cas 交給了 shiro-cas
        /*  PermissionService service = (PermissionService)SpringContextUtil.getBean("PermissionService");
            List<String> codes = service.findPermissionCodeByUsername(username);
            if(codes != null && codes.size() > 0){
                 SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
                     for (String str : codes)
                        {
                            authorizationInfo.addStringPermission(str);
        //                       info.addRole(role);
                        }
                    return authorizationInfo;
            }*/
        
        
        System.out.println(username);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();  
 /*       authorizationInfo.setRoles(userService.findRoles(username));  
        authorizationInfo.setStringPermissions(userService.findPermissions(username));  */
        return authorizationInfo;  
    }
}

複製代碼

\

看看運行效果:

相關文章
相關標籤/搜索