CAS实现SSO(单点登录)

ymc4 10年前

概述

CAS的官网:http://www.jasig.org/cas

演示环境

CentOS 6.5  JDK 1.6  Tomcat 7  CAS-server-3.5.2、CAS-client-3.2.1-release

JDK安装配置

http://hunng.com/2014/04/18/jdk-install-and-config/

keytool安全证书配置

1.生成证书    keytool -genkey -alias ssommall -keyalg RSA -keysize 1024 -keypass mmallcom -validity 365 -keystore /usr/local/src/sso/ssommall.keystore -storepass mmallcom    2.导出证书    keytool -export -alias ssommall -keystore /usr/local/src/sso/ssommall.keystore -file /usr/local/src/sso/ssommall.crt -storepass mmallcom    3.客户端导入证书    keytool -import -keystore %JAVA_HOME%\jre\lib\security\cacerts -file /usr/local/src/sso/ssommall.crt -alias ssommall

部署CAS-Server的Tomcat

在文件 conf/server.xml文件找到:  <!--      <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"                 maxThreads="150" scheme="https" secure="true"                 clientAuth="false" sslProtocol="TLS" />      -->    修改成如下:  <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"                 maxThreads="150" scheme="https" secure="true"                 keystoreFile="g:/sso/ssodemo.keystore" keystorePass="michaelpwd"                 clientAuth="false" sslProtocol="TLS" URIEncoding="UTF-8"    参数说明:  keystoreFile 就是创建证书的路径  keystorePass 就是创建证书的密码

部署CAS-Server

本文以cas-server-3.5.2-release.zip 为例,解压提取cas-server-3.5.2/modules/cas-server-webapp-3.5.2.war文件,并重命名为:cas.war.

CAS-server的默认验证规则:只要用户名和密码相同就认证通过(仅仅用于测试,生成环境需要根据实际情况修改),输入admin/admin 点击登录,就可以看到登录成功的页面。

部署CAS-Client的Tomcat

以cas-client-3.2.1-release.zip 为例,解压提取cas-client-3.2.1/modules/cas-client-core-3.2.1.jar 借以tomcat默认自带的webapps\examples作为演示的简单web项目

安装配置tomcat-demo1

接下来复制 client的lib包cas-client-core-3.2.1.jar到 tomcat-app1\webapps\examples\WEB-INF\lib\目录下, 在tomcat-app1\webapps\examples\WEB-INF\web.xml 文件中增加如下内容:

<!-- ======================== 单点登录开始 ======================== -->      <!-- 用于单点退出,该过滤器用于实现单点登出功能,可选配置-->      <listener>          <listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class>      </listener>        <!-- 该过滤器用于实现单点登出功能,可选配置。 -->      <filter>          <filter-name>CAS Single Sign Out Filter</filter-name>          <filter-class>org.jasig.cas.client.session.SingleSignOutFilter</filter-class>      </filter>      <filter-mapping>          <filter-name>CAS Single Sign Out Filter</filter-name>          <url-pattern>/*</url-pattern>      </filter-mapping>        <filter>          <filter-name>CAS Filter</filter-name>          <filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class>          <init-param>              <param-name>casServerLoginUrl</param-name>              <param-value>https://passport.hunng.com:8443/cas/login</param-value>          </init-param>          <init-param>              <param-name>serverName</param-name>              <param-value>http://demo1.hunng.com:8080</param-value>          </init-param>      </filter>      <filter-mapping>          <filter-name>CAS Filter</filter-name>          <url-pattern>/*</url-pattern>      </filter-mapping>      <!-- 该过滤器负责对Ticket的校验工作,必须启用它 -->      <filter>          <filter-name>CAS Validation Filter</filter-name>          <filter-class>              org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter</filter-class>          <init-param>              <param-name>casServerUrlPrefix</param-name>              <param-value>https://passport.hunng.com:8443/cas</param-value>          </init-param>          <init-param>              <param-name>serverName</param-name>              <param-value>http://demo1.hunng.com:8080</param-value>          </init-param>      </filter>      <filter-mapping>          <filter-name>CAS Validation Filter</filter-name>          <url-pattern>/*</url-pattern>      </filter-mapping>        <!--          该过滤器负责实现HttpServletRequest请求的包裹,          比如允许开发者通过HttpServletRequest的getRemoteUser()方法获得SSO登录用户的登录名,可选配置。      -->      <filter>          <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>          <filter-class>              org.jasig.cas.client.util.HttpServletRequestWrapperFilter</filter-class>      </filter>      <filter-mapping>          <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>          <url-pattern>/*</url-pattern>      </filter-mapping>        <!--      该过滤器使得开发者可以通过org.jasig.cas.client.util.AssertionHolder来获取用户的登录名。      比如AssertionHolder.getAssertion().getPrincipal().getName()。      -->      <filter>          <filter-name>CAS Assertion Thread Local Filter</filter-name>          <filter-class>org.jasig.cas.client.util.AssertionThreadLocalFilter</filter-class>      </filter>      <filter-mapping>          <filter-name>CAS Assertion Thread Local Filter</filter-name>          <url-pattern>/*</url-pattern>      </filter-mapping>        <!-- ======================== 单点登录结束 ======================== -->

有关cas-client的web.xml修改的详细说明见官网介绍: https://wiki.jasig.org/display/CASC/Configuring+the+Jasig+CAS+Client+for+Java+in+the+web.xml

安装配置tomcat-demo2

和tomcat-demo1一样,在这就不啰唆啦。。。

获取登录用户的信息

修改类:webapps\examples\WEB-INF\classes\HelloWorldExample.java 后重新编译并替换 webapps\examples\WEB-INF\classes\HelloWorldExample.class文件。

HelloWorldExample.java 修改后的代码如下:

import java.io.*;  import java.util.*;  import java.util.Map.Entry;    import javax.servlet.*;  import javax.servlet.http.*;    import org.jasig.cas.client.authentication.AttributePrincipal;  import org.jasig.cas.client.util.AbstractCasFilter;  import org.jasig.cas.client.validation.Assertion;    /**   * CAS simple Servlet   *   * @author <a href="http://hunng.com">Hunng</a>   */    public class HelloWorldExample extends HttpServlet {        private static final long serialVersionUID = -1L;        @SuppressWarnings("unchecked")      public void doGet(HttpServletRequest request, HttpServletResponse response)              throws IOException, ServletException {          ResourceBundle rb = ResourceBundle.getBundle("LocalStrings",                  request.getLocale());          response.setContentType("text/html");          PrintWriter out = response.getWriter();            out.println("<html>");          out.println("<head>");            String title = rb.getString("helloworld.title");            out.println("<title>" + title + "</title>");          out.println("</head>");          out.println("<body bgcolor=\"white\">");            out.println("<a href=\"../helloworld.html\">");          out.println("<img src=\"../images/code.gif\" height=24 "                  + "width=24 align=right border=0 alt=\"view code\"></a>");          out.println("<a href=\"../index.html\">");          out.println("<img src=\"../images/return.gif\" height=24 "                  + "width=24 align=right border=0 alt=\"return\"></a>");          out.println("<h1>" + title + "</h1>");            Assertion assertion = (Assertion) request.getSession().getAttribute(                  AbstractCasFilter.CONST_CAS_ASSERTION);            if (null != assertion) {              out.println(" Log | ValidFromDate =:"                      + assertion.getValidFromDate() + "<br>");              out.println(" Log | ValidUntilDate =:"                      + assertion.getValidUntilDate() + "<br>");              Map<Object, Object> attMap = assertion.getAttributes();              out.println(" Log | getAttributes Map size = " + attMap.size()                      + "<br>");              for (Entry<Object, Object> entry : attMap.entrySet()) {                  out.println("     | " + entry.getKey() + "=:"                          + entry.getValue() + "<br>");              }              AttributePrincipal principal = assertion.getPrincipal();                // AttributePrincipal principal = (AttributePrincipal) request              // .getUserPrincipal();                String username = null;              out.print(" Log | UserName:");              if (null != principal) {                  username = principal.getName();                  out.println("<span style='color:red;'>" + username                          + "</span><br>");              }            }            out.println("</body>");          out.println("</html>");      }  }

CAS服务端-配置数据库查询认证机制

在%tomcatcas%/webapps/cas/WEBINF/deployerConfigContext.xml 找到如下信息:

<bean class="org.jasig.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler" />

修改成如下:

<bean class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">      <property name="dataSource" ref="dataSource" ></property>      <property name="sql" value="select password from sso_t_user where login_name=?" ></property>      <property name="passwordEncoder" ref="MD5PasswordEncoder" ></property>  </bean>

同时增加datasource和加密处理两个bean的定义:

<bean id="dataSource"      class="org.springframework.jdbc.datasource.DriverManagerDataSource">      <property name="driverClassName" value="com.mysql.jdbc.Driver" />      <property name="url" value="jdbc:mysql://localhost/test" />      <property name="username" value="root" />      <property name="password" value="" />  </bean>  <bean id="MD5PasswordEncoder"      class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder">      <constructor-arg index="0" value="MD5" />  </bean>

添加相关的jar包

需要在web项目的lib下添加两个包:cas-server-support-jdbc-x.x.x.jar 和 mysql-connector-java-x.x.x-bin.jar