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;  
    }
}

复制代码

\

看看运行效果:

相关文章
相关标签/搜索