Java技术升华

使用spring sercurity+cas实现SSO单点登录

2019-01-29  本文已影响148人  Bitter255

1、cas项目下载

Cas项目可以在GitHub上下载,地址:https://github.com/apereo/cas/releases

本文以cas V4.0.0为例,解压后得到的是cas server的源码,需要把目录下的cas-server-webapp项目加载到idea中。


2、配置cas项目的数据库连接和去掉https请求

配置cas-server

修改%tomcat_home%/webapps/cas/WEB_INF/deployerConfigContext.xml

配置数据库验证bean

 <!-- 数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="minIdle" value="14400"/>
    </bean>

修改authenticationManager

<bean id="authenticationManager" class="org.jasig.cas.authentication.PolicyBasedAuthenticationManager">
        <constructor-arg>
            <map>
                <!--
                   | IMPORTANT
                   | Every handler requires a unique name.
                   | If more than one instance of the same handler class is configured, you must explicitly
                   | set its name to something other than its default name (typically the simple class name).
                   -->
                <entry key-ref="proxyAuthenticationHandler" value-ref="proxyPrincipalResolver" />
                <entry key-ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" />
            </map>
        </constructor-arg>

添加一个entry,primaryAuthenticationHandler。

创建自定义密码校验处理类

 <bean id="primaryAuthenticationHandler" class="com.imec.authentication.handler.MyAuthenticationHandler">
        <property name="dataSource" ref="dataSource"/>
        <property name="sql" value="SELECT password, salt, status FROM t_account_cas WHERE name=?"/>
    </bean>

创建一个自定义的密码校验类MyAuthenticationHandler,继承AbstractJdbcUsernamePasswordAuthenticationHandler,
进行密码校验。

 @Override
    protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential usernamePasswordCredential) throws GeneralSecurityException, PreventedException {
        final String username = usernamePasswordCredential.getUsername();
        final String password = usernamePasswordCredential.getPassword();
        try {
            final Map<String, Object> values = getJdbcTemplate().queryForMap(this.sql, username);
            String dbPassword = (String) values.get("password");
            String salt = (String) values.get("salt");
            salt=username+salt;
            Integer status = (Integer) values.get("status");
            if(!status.equals(1)) { //判断帐号是否被冻结
                throw new AccountLockedException("This user is disabled.");
            }

            //密码加盐并迭代1024次
            String encryptedPassword = new Md5Hash(usernamePasswordCredential.getPassword(), salt, 2).toHex();
            if (!dbPassword.equals(encryptedPassword)) {
                throw new FailedLoginException("Password does not match value on record.");
            }
        } catch (final IncorrectResultSizeDataAccessException e) {
            if (e.getActualSize() == 0) {
                throw new AccountNotFoundException(username + " not found with SQL query");
            } else {
                throw new FailedLoginException("Multiple records found for " + username);
            }
        } catch (final DataAccessException e) {
            e.printStackTrace();
            throw new PreventedException("SQL exception while executing query for " + username, e);
        }
        return createHandlerResult(usernamePasswordCredential, new SimplePrincipal(username), null);
    }

去掉https验证

cas默认是采用https模式的,我们没有配置证书,所以去掉https验证取消https的过滤,让http协议也能访问
4.0.0 版本一共需要修改三个地方

修改deployerConfigContext.xml添加p:requireSecure=”false”

cas/WEB-INF/deployerConfigContext.xml

 <!-- Required for proxy ticket mechanism. -->
    <bean id="proxyAuthenticationHandler"
          class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"
          p:httpClient-ref="httpClient" p:requireSecure="false" />

修改ticketGrantingTicketCookieGenerator.xml修改p:cookieSecure=”false”

cas/WEB-INF/spring-configuration/ticketGrantingTicketCookieGenerator.xml

<bean id="ticketGrantingTicketCookieGenerator" class="org.jasig.cas.web.support.CookieRetrievingCookieGenerator"
        p:cookieSecure="false"
        p:cookieMaxAge="-1"
        p:cookieName="CASTGC"
        p:cookiePath="/cas" />

修改warnCookieGenerator.xml修改p:cookieSecure=”false”

cas/WEB-INF/spring-configuration/warnCookieGenerator.xml

<bean id="warnCookieGenerator" class="org.jasig.cas.web.support.CookieRetrievingCookieGenerator"
        p:cookieSecure="false"
        p:cookieMaxAge="-1"
        p:cookieName="CASPRIVACY"
        p:cookiePath="/cas" />

3、spring security 和cas的集成

修改spring-sercurity.xml
1、配置一个cas地址的properties文件。

#cas server login address
cas_server_login=http://localhost:8084/cas/login

#cas server login successful return localhost address
localhost_server=http://localhost:8080/nsycManager/j_spring_cas_security_check

#cas server ticket validator address
cas_server_address=http://localhost:8084/cas

#cas server logout successful return localhost address
cas_server_logout=http://localhost:8084/cas/logout?service=http://localhost:8080/nsycManager/login

2、设置spring sercurity的自动拦截设置为false,配置一个进入cas的认证入口casAuthEntryPoint。在拦截器里配置一个自定义的cas认证过滤器、一个注销客户端和一个注销session的服务器端的过滤器。

<!-- cas地址配置 -->
    <beans:bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="order" value="1"/>
        <beans:property name="ignoreUnresolvablePlaceholders" value="true"/>
        <beans:property name="location" value="classpath:cas.properties"/>
    </beans:bean>


    <!-- 不要过滤图片等静态资源 -->
    <http  pattern="/resources/**" security="none"/>

    <!-- cas拦截规则 -->
    <http auto-config="false" entry-point-ref="casAuthEntryPoint" servlet-api-provision="true">


        <intercept-url pattern="login" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
        <intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>

        <session-management invalid-session-url="/login"/>
        <!-- cas 认证过滤器 -->
        <custom-filter ref="casFilter" position="CAS_FILTER"/>
        <!-- 注销服务器端 -->
        <custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER"/>
        <!-- 注销客户端 -->
        <custom-filter ref="singleLogoutFilter" before="CAS_FILTER"/>
    </http>
<!-- CAS认证切入点,声明cas服务器端登录的地址 -->
    <beans:bean id="casAuthEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
        <beans:property name="loginUrl" value="${cas_server_login}"/>
        <beans:property name="serviceProperties" ref="casService"/>
    </beans:bean>

    <!-- 登录成功后的返回地址 -->
    <beans:bean id="casService" class="org.springframework.security.cas.ServiceProperties">
        <beans:property name="service" value="${localhost_server}"/>
        <beans:property name="sendRenew" value="false"/>
    </beans:bean>

认证入口里配置一个cas的登录地址,和一个认证成功后当前项目的返回地址。
3、配置cas认证过滤器

<!-- cas 认证过滤器 -->
    <beans:bean id="casFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">
        <beans:property name="authenticationManager" ref="authenticationManager"/>
        <beans:property name="authenticationFailureHandler" ref="authenticationFailureHandler"/>
        <beans:property name="authenticationSuccessHandler" ref="authenticationSuccessHandler"/>
        <beans:property name="filterProcessesUrl" value="/j_spring_cas_security_check"/>
    </beans:bean>

    <!-- 在认证管理器中注册cas认证提供器 -->
    <authentication-manager alias="authenticationManager">
        <authentication-provider ref="casAuthenticationProvider"/>
    </authentication-manager>

    <!-- cas认证提供器,定义客户端的验证方式 -->
    <beans:bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
        <beans:property name="ticketValidator" ref="casTicketValidator"/>
        <beans:property name="serviceProperties" ref="casService"/>
        <beans:property name="key" value="an_id_for_this_auth_provider_only"/>
        <beans:property name="authenticationUserDetailsService" ref="authenticationUserDetailsService"/>
    </beans:bean>

    <!-- 配置ticket validator -->
    <beans:bean id="casTicketValidator" class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
        <beans:constructor-arg index="0" value="${cas_server_address}"/>
    </beans:bean>

    <beans:bean id="authenticationUserDetailsService" class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
        <beans:property name="userDetailsService" ref="basicUserDetailsService"/>
    </beans:bean>

    <beans:bean id="basicUserDetailsService"
                class="com.imec.air.ctrl.mgr.auth.security.authentication.BasicUserDetailsServiceImpl">
    </beans:bean>

    <!-- cas 认证失败控制器 -->
    <beans:bean id="authenticationFailureHandler" class="com.imec.air.ctrl.mgr.auth.security.authentication.BasicAuthenticationFailureHandler">
        <beans:property name="defaultFailureUrl" value="/login.jsp?error=true"/>
    </beans:bean>

    <!-- cas 认证成功控制器 -->
    <beans:bean id="authenticationSuccessHandler" class="com.imec.air.ctrl.mgr.auth.security.authentication.BasicAuthenticationSuccessHandler">

    </beans:bean>

配置一个拦截登录请求的URL地址、配置一个cas认证提供器、配置认证过滤器成功跳转方法和失败跳转方法。其中cas认证提供器里配置有cas的ticket的校验类casTicketValidator、ticket认证成功后返回的当前项目的地址、校验方式和UserDetailsService的实现类。
4、注销客户端过滤器

    <!-- 注销客户端 -->
    <beans:bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter" />

5、注销服务器端过滤器

<!-- 注销服务器端 -->
    <beans:bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
        <!--<beans:property name="filterProcessesUrl" value="/j_spring_cas_security_logout"/>-->
        <beans:constructor-arg value="${cas_server_logout}"/>
        <beans:constructor-arg>
            <beans:bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
        </beans:constructor-arg>
        <!--<beans:property name="filterProcessesUrl" value="/j_spring_cas_security_logout"/>-->
         <beans:property name="filterProcessesUrl" value="/j_spring_cas_security_logout"/>
        <!--<beans:property name="filterProcessesUrl" value="/cas/logout"/>-->
    </beans:bean>

注销服务器端的过滤器中,配置一个服务器的注销地址和当前项目退出操作的URL地址。

注意:服务器的注销地址中可以带一个注销成功后的回调地址。

cas_server_logout=http://localhost:8084/cas/logout?service=http://localhost:8080/nsycManager/login

需要配置cas项目
WEB-INF/cas.properties文件 改成true

##
# CAS Logout Behavior
# WEB-INF/cas-servlet.xml
#
# Specify whether CAS should redirect to the specified service parameter on /logout requests
 cas.logout.followServiceRedirects=true

注意:cas要和spring security集成,还需要添加spring-security-cas和cas-client-core这两个架包。
到此,spring sercurity和cas实现SSO单点登录完成。

上一篇下一篇

猜你喜欢

热点阅读