yale cas4.0 项目集成示例(附带示例工程)

yale cas 统一身份认证, 公司用的版本是3.5 ,我用最新版本4.0做了个cas 简单集成示例, 实现单点登录登出, 和3.5 有很多不同,除了代码和配置有很大的优化,其中把服务管理 做为一个独立工程,比之前好很多。


cas 官方文档:http://jasig.github.io/cas/4.0.x/index.html

  1.  导入cas4.0.0项目 (从github上下载)


  2.  解决导入工程编译报错

       修改主项目pom文件,追加红色部分,大部分编译正常了,

      有几个项目由于缺少包: Missing artifact org.samba.jcifs:jcifs-ext:jar:0.9.4,Missing artifact org.samba.jcifs:jcifs:jar:1.2.25(我用不到这个项目就不箮了,把相关地方注释)

       

 <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.jasig.maven</groupId>
                                        <artifactId>maven-translate-plugin</artifactId>
                                        <versionRange>[0.0.1,)</versionRange>
                                        <goals>
                                            <goal>check</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore />
                                    </action>
                                </pluginExecution>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.apache.maven.plugins</groupId>
                                        <artifactId>maven-enforcer-plugin</artifactId>
                                        <versionRange>[1.0.0,)</versionRange>
                                        <goals>
                                            <goal>enforce</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore />
                                    </action>
                                </pluginExecution>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.apache.maven.plugins</groupId>
                                        <artifactId>maven-checkstyle-plugin</artifactId>
                                        <versionRange>[2.1.0,)</versionRange>
                                        <goals>
                                            <goal>checkstyle</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore />
                                    </action>
                                </pluginExecution>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.codehaus.mojo</groupId>
                                        <artifactId>aspectj-maven-plugin</artifactId>
                                        <goals>
                                            <goal>compile</goal>
                                        </goals>
                                        <versionRange>[1.4,)</versionRange>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore />
                                    </action>
                                </pluginExecution>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>com.mycila.maven-license-plugin</groupId>
                                        <artifactId>maven-license-plugin</artifactId>
                                        <goals>
                                            <goal>check</goal>
                                        </goals>
                                        <versionRange>[1.9,)</versionRange>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore />
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>

     pom中增加上面部分,如果pom文件报错
     打包报错 主项目pom文件注释掉maven-license-plugin


3. web工程 加入jetty插件 (我都是采用maven jetty运行)

拷贝

jetty-env.xml (不需要jndi,就不需要这配置)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
    <!-- 应用数据源 -->
    <New id="showcase" class="org.eclipse.jetty.plus.jndi.Resource">
        <Arg>jdbc/EnvconfigDB</Arg>
        <Arg>
            <New class="org.apache.commons.dbcp.BasicDataSource">
                <Set name="driverClassName">com.mysql.jdbc.Driver</Set>
                <Set name="url">jdbc:mysql://172.16.30.54:3306/ce_demo_config?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8</Set>
                <Set name="username">root</Set>
                <Set name="password">111111</Set>
                <Set name="maxActive">2</Set>
            </New>
        </Arg>
    </New>
</Configure> 


webdefault.xml (window系统下开发,运行maven jetty需要这配置)

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
   metadata-complete="false"
   version="3.1"> 

  <!-- ===================================================================== -->
  <!-- This file contains the default descriptor for web applications.       -->
  <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
  <!-- The intent of this descriptor is to include jetty specific or common  -->
  <!-- configuration for all webapps.   If a context has a webdefault.xml    -->
  <!-- descriptor, it is applied before the contexts own web.xml file        -->
  <!--                                                                       -->
  <!-- A context may be assigned a default descriptor by:                    -->
  <!--  + Calling WebApplicationContext.setDefaultsDescriptor                -->
  <!--  + Passed an arg to addWebApplications                                -->
  <!--                                                                       -->
  <!-- This file is used both as the resource within the jetty.jar (which is -->
  <!-- used as the default if no explicit defaults descriptor is set) and it -->
  <!-- is copied to the etc directory of the Jetty distro and explicitly     -->
  <!-- by the jetty.xml file.                                                -->
  <!--                                                                       -->
  <!-- ===================================================================== -->

  <description>
    Default web.xml file.  
    This file is applied to a Web application before it's own WEB_INF/web.xml file
  </description>

  <!-- ==================================================================== -->
  <!-- Removes static references to beans from javax.el.BeanELResolver to   -->
  <!-- ensure webapp classloader can be released on undeploy                -->
  <!-- ==================================================================== -->
  <listener>
   <listener-class>org.eclipse.jetty.servlet.listener.ELContextCleaner</listener-class>
  </listener>
  
  <!-- ==================================================================== -->
  <!-- Removes static cache of Methods from java.beans.Introspector to      -->
  <!-- ensure webapp classloader can be released on undeploy                -->
  <!-- ==================================================================== -->  
  <listener>
   <listener-class>org.eclipse.jetty.servlet.listener.IntrospectorCleaner</listener-class>
  </listener>
  

  <!-- ==================================================================== -->
  <!-- Context params to control Session Cookies                            -->
  <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  -->
  <!--
    UNCOMMENT TO ACTIVATE 
    <context-param> 
      <param-name>org.eclipse.jetty.servlet.SessionDomain</param-name> 
      <param-value>127.0.0.1</param-value> 
    </context-param> 
    <context-param>
      <param-name>org.eclipse.jetty.servlet.SessionPath</param-name>
      <param-value>/</param-value>
    </context-param>
    <context-param>
      <param-name>org.eclipse.jetty.servlet.MaxAge</param-name>
      <param-value>-1</param-value>
    </context-param>
  -->
    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>PROPERTIES</param-value>
<!--         <param-value>JNDI</param-value> -->
    </context-param>
    
  <resource-ref>  
    <description>MySQL DataSource Reference</description>  
    <res-ref-name>jdbc/EnvconfigDB</res-ref-name>  
    <res-type>javax.sql.DataSource</res-type>  
    <res-auth>Container</res-auth>  
  </resource-ref>  
    

  <!-- ==================================================================== -->
  <!-- The default servlet.                                                 -->
  <!-- This servlet, normally mapped to /, provides the handling for static -->
  <!-- content, OPTIONS and TRACE methods for the context.                  -->
  <!-- The following initParameters are supported:                          -->
  <!--  
 *  acceptRanges      If true, range requests and responses are
 *                    supported
 *
 *  dirAllowed        If true, directory listings are returned if no
 *                    welcome file is found. Else 403 Forbidden.
 *
 *  welcomeServlets   If true, attempt to dispatch to welcome files
 *                    that are servlets, but only after no matching static
 *                    resources could be found. If false, then a welcome
 *                    file must exist on disk. If "exact", then exact
 *                    servlet matches are supported without an existing file.
 *                    Default is true.
 *
 *                    This must be false if you want directory listings,
 *                    but have index.jsp in your welcome file list.
 *
 *  redirectWelcome   If true, welcome files are redirected rather than
 *                    forwarded to.
 *
 *  gzip              If set to true, then static content will be served as
 *                    gzip content encoded if a matching resource is
 *                    found ending with ".gz"
 *
 *  resourceBase      Set to replace the context resource base
 *
 *  resourceCache     If set, this is a context attribute name, which the servlet
 *                    will use to look for a shared ResourceCache instance.
 *
 *  relativeResourceBase
 *                    Set with a pathname relative to the base of the
 *                    servlet context root. Useful for only serving static content out
 *                    of only specific subdirectories.
 *
 *  pathInfoOnly      If true, only the path info will be applied to the resourceBase
 *
 *  stylesheet        Set with the location of an optional stylesheet that will be used
 *                    to decorate the directory listing html.
 *
 *  aliases           If True, aliases of resources are allowed (eg. symbolic
 *                    links and caps variations). May bypass security constraints.
 *                    
 *  etags             If True, weak etags will be generated and handled.
 *
 *  maxCacheSize      The maximum total size of the cache or 0 for no cache.
 *  maxCachedFileSize The maximum size of a file to cache
 *  maxCachedFiles    The maximum number of files to cache
 *
 *  useFileMappedBuffer
 *                    If set to true, it will use mapped file buffer to serve static content
 *                    when using NIO connector. Setting this value to false means that
 *                    a direct buffer will be used instead of a mapped file buffer.
 *                    By default, this is set to true.
 *
 *  cacheControl      If set, all static content will have this value set as the cache-control
 *                    header.
 *
 -->
 
 
  <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  -->
  <servlet>
    <servlet-name>default</servlet-name>
    <servlet-class>org.eclipse.jetty.servlet.DefaultServlet</servlet-class>
    <init-param>
      <param-name>aliases</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>acceptRanges</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>dirAllowed</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>welcomeServlets</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>redirectWelcome</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>maxCacheSize</param-name>
      <param-value>256000000</param-value>
    </init-param>
    <init-param>
      <param-name>maxCachedFileSize</param-name>
      <param-value>200000000</param-value>
    </init-param>
    <init-param>
      <param-name>maxCachedFiles</param-name>
      <param-value>2048</param-value>
    </init-param>
    <init-param>
      <param-name>gzip</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>etags</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>useFileMappedBuffer</param-name>
      <param-value>false</param-value>
    </init-param>
    <!--
    <init-param>
      <param-name>resourceCache</param-name>
      <param-value>resourceCache</param-value>
    </init-param>
    -->
    <!--
    <init-param>
      <param-name>cacheControl</param-name>
      <param-value>max-age=3600,public</param-value>
    </init-param>
    -->
    <load-on-startup>0</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <!-- ==================================================================== -->
  <!-- JSP Servlet                                                          -->
  <!-- This is the jasper JSP servlet from the jakarta project              -->
  <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  -->
  <!-- The JSP page compiler and execution servlet, which is the mechanism  -->
  <!-- used by Glassfish to support JSP pages.  Traditionally, this servlet -->
  <!-- is mapped to URL patterh "*.jsp".  This servlet supports the         -->
  <!-- following initialization parameters (default values are in square    -->
  <!-- brackets):                                                           -->
  <!--                                                                      -->
  <!--   checkInterval       If development is false and reloading is true, -->
  <!--                       background compiles are enabled. checkInterval -->
  <!--                       is the time in seconds between checks to see   -->
  <!--                       if a JSP page needs to be recompiled. [300]    -->
  <!--                                                                      -->
  <!--   compiler            Which compiler Ant should use to compile JSP   -->
  <!--                       pages.  See the Ant documenation for more      -->
  <!--                       information. [javac]                           -->
  <!--                                                                      -->
  <!--   classdebuginfo      Should the class file be compiled with         -->
  <!--                       debugging information?  [true]                 -->
  <!--                                                                      -->
  <!--   classpath           What class path should I use while compiling   -->
  <!--                       generated servlets?  [Created dynamically      -->
  <!--                       based on the current web application]          -->
  <!--                       Set to ? to make the container explicitly set  -->
  <!--                       this parameter.                                -->
  <!--                                                                      -->
  <!--   development         Is Jasper used in development mode (will check -->
  <!--                       for JSP modification on every access)?  [true] -->
  <!--                                                                      -->
  <!--   enablePooling       Determines whether tag handler pooling is      -->
  <!--                       enabled  [true]                                -->
  <!--                                                                      -->
  <!--   fork                Tell Ant to fork compiles of JSP pages so that -->
  <!--                       a separate JVM is used for JSP page compiles   -->
  <!--                       from the one Tomcat is running in. [true]      -->
  <!--                                                                      -->
  <!--   ieClassId           The class-id value to be sent to Internet      -->
  <!--                       Explorer when using <jsp:plugin> tags.         -->
  <!--                       [clsid:8AD9C840-044E-11D1-B3E9-00805F499D93]   -->
  <!--                                                                      -->
  <!--   javaEncoding        Java file encoding to use for generating java  -->
  <!--                       source files. [UTF-8]                          -->
  <!--                                                                      -->
  <!--   keepgenerated       Should we keep the generated Java source code  -->
  <!--                       for each page instead of deleting it? [true]   -->
  <!--                                                                      -->
  <!--   logVerbosityLevel   The level of detailed messages to be produced  -->
  <!--                       by this servlet.  Increasing levels cause the  -->
  <!--                       generation of more messages.  Valid values are -->
  <!--                       FATAL, ERROR, WARNING, INFORMATION, and DEBUG. -->
  <!--                       [WARNING]                                      -->
  <!--                                                                      -->
  <!--   mappedfile          Should we generate static content with one     -->
  <!--                       print statement per input line, to ease        -->
  <!--                       debugging?  [false]                            -->
  <!--                                                                      -->
  <!--                                                                      -->
  <!--   reloading           Should Jasper check for modified JSPs?  [true] -->
  <!--                                                                      -->
  <!--   suppressSmap        Should the generation of SMAP info for JSR45   -->
  <!--                       debugging be suppressed?  [false]              -->
  <!--                                                                      -->
  <!--   dumpSmap            Should the SMAP info for JSR45 debugging be    -->
  <!--                       dumped to a file? [false]                      -->
  <!--                       False if suppressSmap is true                  -->
  <!--                                                                      -->
  <!--   scratchdir          What scratch directory should we use when      -->
  <!--                       compiling JSP pages?  [default work directory  -->
  <!--                       for the current web application]               -->
  <!--                                                                      -->
  <!--   tagpoolMaxSize      The maximum tag handler pool size  [5]         -->
  <!--                                                                      -->
  <!--   xpoweredBy          Determines whether X-Powered-By response       -->
  <!--                       header is added by generated servlet  [false]  -->
  <!--                                                                      -->
  <!-- If you wish to use Jikes to compile JSP pages:                       -->
  <!--   Set the init parameter "compiler" to "jikes".  Define              -->
  <!--   the property "-Dbuild.compiler.emacs=true" when starting Jetty     -->
  <!--   to cause Jikes to emit error messages in a format compatible with  -->
  <!--   Jasper.                                                            -->
  <!--   If you get an error reporting that jikes can't use UTF-8 encoding, -->
  <!--   try setting the init parameter "javaEncoding" to "ISO-8859-1".     -->
  <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  -->
  <servlet id="jsp">
    <servlet-name>jsp</servlet-name>
    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <init-param>
      <param-name>logVerbosityLevel</param-name>
      <param-value>DEBUG</param-value>
    </init-param>
    <init-param>
      <param-name>fork</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>xpoweredBy</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>compilerTargetVM</param-name>
      <param-value>1.7</param-value>
    </init-param>
    <init-param>
      <param-name>compilerSourceVM</param-name>
      <param-value>1.7</param-value>
    </init-param>
    <!--  
    <init-param>
        <param-name>classpath</param-name>
        <param-value>?</param-value>
    </init-param>
    -->
    <load-on-startup>0</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.jsp</url-pattern>
    <url-pattern>*.jspf</url-pattern>
    <url-pattern>*.jspx</url-pattern>
    <url-pattern>*.xsp</url-pattern>
    <url-pattern>*.JSP</url-pattern>
    <url-pattern>*.JSPF</url-pattern>
    <url-pattern>*.JSPX</url-pattern>
    <url-pattern>*.XSP</url-pattern>
  </servlet-mapping>


  <!-- ==================================================================== -->
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>

  <!-- ==================================================================== -->
  <!-- Default MIME mappings                                                -->
  <!-- The default MIME mappings are provided by the mime.properties        -->
  <!-- resource in the org.eclipse.jetty.server.jar file.  Additional or modified  -->
  <!-- mappings may be specified here                                       -->
  <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  -->
  <!-- UNCOMMENT TO ACTIVATE
  <mime-mapping>
    <extension>mysuffix</extension>
    <mime-type>mymime/type</mime-type>
  </mime-mapping>
  -->

  <!-- ==================================================================== -->
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!-- ==================================================================== -->
  <locale-encoding-mapping-list>
    <locale-encoding-mapping>
      <locale>ar</locale>
      <encoding>ISO-8859-6</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>be</locale>
      <encoding>ISO-8859-5</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>bg</locale>
      <encoding>ISO-8859-5</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>ca</locale>
      <encoding>ISO-8859-1</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>cs</locale>
      <encoding>ISO-8859-2</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>da</locale>
      <encoding>ISO-8859-1</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>de</locale>
      <encoding>ISO-8859-1</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>el</locale>
      <encoding>ISO-8859-7</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>en</locale>
      <encoding>ISO-8859-1</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>es</locale>
      <encoding>ISO-8859-1</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>et</locale>
      <encoding>ISO-8859-1</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>fi</locale>
      <encoding>ISO-8859-1</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>fr</locale>
      <encoding>ISO-8859-1</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>hr</locale>
      <encoding>ISO-8859-2</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>hu</locale>
      <encoding>ISO-8859-2</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>is</locale>
      <encoding>ISO-8859-1</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>it</locale>
      <encoding>ISO-8859-1</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>iw</locale>
      <encoding>ISO-8859-8</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>ja</locale>
      <encoding>Shift_JIS</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>ko</locale>
      <encoding>EUC-KR</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>lt</locale>
      <encoding>ISO-8859-2</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>lv</locale>
      <encoding>ISO-8859-2</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>mk</locale>
      <encoding>ISO-8859-5</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>nl</locale>
      <encoding>ISO-8859-1</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>no</locale>
      <encoding>ISO-8859-1</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>pl</locale>
      <encoding>ISO-8859-2</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>pt</locale>
      <encoding>ISO-8859-1</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>ro</locale>
      <encoding>ISO-8859-2</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>ru</locale>
      <encoding>ISO-8859-5</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>sh</locale>
      <encoding>ISO-8859-5</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>sk</locale>
      <encoding>ISO-8859-2</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>sl</locale>
      <encoding>ISO-8859-2</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>sq</locale>
      <encoding>ISO-8859-2</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>sr</locale>
      <encoding>ISO-8859-5</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>sv</locale>
      <encoding>ISO-8859-1</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>tr</locale>
      <encoding>ISO-8859-9</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>uk</locale>
      <encoding>ISO-8859-5</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>zh</locale>
      <encoding>GB2312</encoding>
    </locale-encoding-mapping>
    <locale-encoding-mapping>
      <locale>zh_TW</locale>
      <encoding>Big5</encoding>
    </locale-encoding-mapping>
  </locale-encoding-mapping-list>

  <security-constraint>
    <web-resource-collection>
      <web-resource-name>Disable TRACE</web-resource-name>
      <url-pattern>/</url-pattern>
      <http-method>TRACE</http-method>
    </web-resource-collection>
    <auth-constraint/>
  </security-constraint>
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>Enable everything but TRACE</web-resource-name>
      <url-pattern>/</url-pattern>
      <http-method-ommission>TRACE</http-method-ommission>
    </web-resource-collection>
  </security-constraint>

</web-app>

建立上面两个文件放到 resources下

在pom.xml里增加

 

<plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <configuration>
                    <war>${project.build.directory}/${project.artifactId}.war</war>
                    <scanIntervalSeconds>0</scanIntervalSeconds>
                    <jettyXml>src/main/resources/jetty-env.xml</jettyXml>
                    <webApp>
                        <contextPath>/</contextPath>
                        <defaultsDescriptor>src/main/resources/webdefault.xml
                        </defaultsDescriptor>
                    </webApp>
                    <httpConnector>
                        <port>8080</port>
                        <idleTimeout>6000</idleTimeout>
                    </httpConnector>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>commons-dbcp</groupId>
                        <artifactId>commons-dbcp</artifactId>
                        <version>1.4</version>
                    </dependency>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.21</version>
                    </dependency>
                </dependencies>
            </plugin>


 4. 本地测试去掉ssl

   增加或修改红色部分

  deployerConfigContext.xml

 <bean id="proxyAuthenticationHandler"

          class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"

          p:httpClient-ref="httpClient" p:requireSecure="false" />


 ticketGrantingTicketCookieGenerator.xml

<bean id="ticketGrantingTicketCookieGenerator" class="org.jasig.cas.web.support.CookieRetrievingCookieGenerator"

p:cookieSecure="false"

p:cookieMaxAge="-1"

p:cookieName="CASTGC"

p:cookiePath="/cas" />


去掉登录页警告,直接注释这段

<c:if test="${not pageContext.request.secure}">

...

</c:if>



5. 修改配置

cas-server-webapp工程

修改cas.properties

//(jetty运行去掉上下文路径,不是必要)

server.prefix=${server.name}     

增加登出

cas.securityContext.casProcessingFilterEntryPoint.logoutUrl=${server.prefix}/logout


cas-management-webapp工程

cas-management.properties

//(jetty运行去掉上下文路径,不是必要)

cas.prefix=${cas.host}

cas-management.prefix=http://localhost:8088

增加登出

cas.securityContext.casProcessingFilterEntryPoint.logoutUrl=${cas.prefix}/logout


修改相关jsp:

viewjsp/default/ui/includes/bottom.jsp或者viewjsp/ui/includes/bottom.jsp (远程太慢,而且有个文件404,自己下载相关版本到js目录)

<!--     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> -->

<!--     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> -->

    <script type="text/javascript" src="jquery/jquery-1.11.1.min.js"></script>

    <script type="text/javascript" src="jquery/jquery-ui-1.10.4.custom.min.js"></script>


NOTE: cas-management-webapp view/ui/logout.jsp  内容替换成

//url可以按你的方式取到,这里集成了我的env工具

<%
final String url = com.sunkey.common.env.ConfigHolder.getString("cas.securityContext.casProcessingFilterEntryPoint.logoutUrl");
response.sendRedirect(response.encodeURL(url));
%>
cas-server-webapp  view/jsp/default/ui/casLogoutView.jsp  内容替换成
<%
String queryString = request.getQueryString();
// queryString = request.getContextPath() + "/login" + (queryString != null ? "?" + queryString : "?service=" + com.fpx.common.env.ConfigHolder.getString("default.login.app.service"));
String url = com.sunkey.common.env.ConfigHolder.getString("cas.securityContext.casProcessingFilterEntryPoint.loginUrl") + (queryString != null ? "?" + queryString : "") ;
response.sendRedirect(response.encodeURL(url));
%>

6. 测试

  cas-server-webapp 和cas-management-webapp 分别jetty:run -DskipTests

http://localhost:8088  访问management会自动跳到http://localhost:8080/login 登录,填写用户密码登录后跳转到


NOTE: 默认用户casuser:Mellon, deployerConfigContext里,primaryAuthenticationHandler这个bean配置


7. 其它 :

默认用户修改:

  在deployerConfigContext.xml中

 <bean id="primaryAuthenticationHandler"
          class="org.jasig.cas.authentication.AcceptUsersAuthenticationHandler">
        <property name="users">
            <map>
                <entry key="zhouxq" value="fpx@1234"/>
            </map>
        </property>
    </bean>

我修改后的全部配置, 已经集成了jdbc,你可注释掉dababase部分配置,打开stub注释部分。

<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to Jasig under one or more contributor license
    agreements. See the NOTICE file distributed with this work
    for additional information regarding copyright ownership.
    Jasig licenses this file to you under the Apache License,
    Version 2.0 (the "License"); you may not use this file
    except in compliance with the License.  You may obtain a
    copy of the License at the following location:

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

-->
<!--
| deployerConfigContext.xml centralizes into one file some of the declarative configuration that
| all CAS deployers will need to modify.
|
| This file declares some of the Spring-managed JavaBeans that make up a CAS deployment.  
| The beans declared in this file are instantiated at context initialization time by the Spring 
| ContextLoaderListener declared in web.xml.  It finds this file because this
| file is among those declared in the context parameter "contextConfigLocation".
|
| By far the most common change you will need to make in this file is to change the last bean
| declaration to replace the default authentication handler with
| one implementing your approach for authenticating usernames and passwords.
+-->

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:sec="http://www.springframework.org/schema/security"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!--
       | The authentication manager defines security policy for authentication by specifying at a minimum
       | the authentication handlers that will be used to authenticate credential. While the AuthenticationManager
       | interface supports plugging in another implementation, the default PolicyBasedAuthenticationManager should
       | be sufficient in most cases.
       +-->
    <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" />
                <!-- stub -->
<!--                 <entry key-ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" /> -->
                <!-- database -->
                <entry key-ref="queryDatabaseSaltAuthenticationHandler" value-ref="primaryJdbcPrincipalResolver" />
            </map>
        </constructor-arg>

        <!-- Uncomment the metadata populator to allow clearpass to capture and cache the password
             This switch effectively will turn on clearpass.
        <property name="authenticationMetaDataPopulators">
           <util:list>
              <bean class="org.jasig.cas.extension.clearpass.CacheCredentialsMetaDataPopulator"
                    c:credentialCache-ref="encryptedMap" />
           </util:list>
        </property>
        -->

        <!--
           | Defines the security policy around authentication. Some alternative policies that ship with CAS:
           |
           | * NotPreventedAuthenticationPolicy - all credential must either pass or fail authentication
           | * AllAuthenticationPolicy - all presented credential must be authenticated successfully
           | * RequiredHandlerAuthenticationPolicy - specifies a handler that must authenticate its credential to pass
           -->
        <property name="authenticationPolicy">
            <bean class="org.jasig.cas.authentication.AnyAuthenticationPolicy" />
        </property>
    </bean>

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

    <!--
       | TODO: Replace this component with one suitable for your enviroment.
       |
       | This component provides authentication for the kind of credential used in your environment. In most cases
       | credential is a username/password pair that lives in a system of record like an LDAP directory.
       | The most common authentication handler beans:
       |
       | * org.jasig.cas.authentication.LdapAuthenticationHandler
       | * org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler
       | * org.jasig.cas.adaptors.x509.authentication.handler.support.X509CredentialsAuthenticationHandler
       | * org.jasig.cas.support.spnego.authentication.handler.support.JCIFSSpnegoAuthenticationHandler
       -->
    <bean id="primaryAuthenticationHandler"
          class="org.jasig.cas.authentication.AcceptUsersAuthenticationHandler">
        <property name="users">
            <map>
                <entry key="zhouxq" value="fpx@1234"/>
            </map>
        </property>
    </bean>
    
    <bean id="passwordEncoder"
      class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder"
      c:encodingAlgorithm="MD5"
      p:characterEncoding="UTF-8" />

    <!-- Required for proxy ticket mechanism -->
    <bean id="proxyPrincipalResolver"
          class="org.jasig.cas.authentication.principal.BasicPrincipalResolver" />

    <!--
       | Resolves a principal from a credential using an attribute repository that is configured to resolve
       | against a deployer-specific store (e.g. LDAP).
       -->
    <bean id="primaryPrincipalResolver"
          class="org.jasig.cas.authentication.principal.PersonDirectoryPrincipalResolver" >
        <property name="attributeRepository" ref="attributeRepository" />
    </bean>

    <!--
    Bean that defines the attributes that a service may return.  This example uses the Stub/Mock version.  A real implementation
    may go against a database or LDAP server.  The id should remain "attributeRepository" though.
    +-->
    <bean id="attributeRepository" class="org.jasig.services.persondir.support.StubPersonAttributeDao"
            p:backingMap-ref="attrRepoBackingMap" />
    
    <util:map id="attrRepoBackingMap">
        <entry key="uid" value="uid" />
        <entry key="eduPersonAffiliation" value="eduPersonAffiliation" /> 
        <entry key="groupMembership" value="groupMembership" />
    </util:map>
    
    <!-- dababase -->
    <bean id="queryDatabaseSaltAuthenticationHandler" class="org.jasig.cas.adaptors.jdbc.QueryDatabaseSaltAuthenticationHandler"
         p:dataSource-ref="dataSource" p:passwordEncoder-ref="passwordEncoder">
        <property name="sql" value="SELECT password, salt, login_name, alias FROM staff WHERE status = 'NORMAL' and login_name=?" />
    </bean>
    <bean id="primaryJdbcPrincipalResolver" class="org.jasig.cas.authentication.principal.PersonDirectoryPrincipalResolver">
        <property name="attributeRepository" ref="jdbcAttributeRepository" />
    </bean>
    <bean id="jdbcAttributeRepository" class="org.jasig.services.persondir.support.jdbc.SingleRowJdbcPersonAttributeDao">
        <constructor-arg index="0" ref="dataSource" />
        <constructor-arg index="1" value="select s.id, s.real_name, s.alias, s.mobile, s.email, s.sex from staff s  where {0}" />
        <property name="queryAttributeMapping">
            <map>
                <entry key="username" value="login_name" />
            </map>
        </property>
        <property name="resultAttributeMapping">
            <map>
                <entry key="real_name" value="realName" />
                <entry key="alias" value="alias" />
                <entry key="mobile" value="mobile" />
                <entry key="email" value="email" />
                <entry key="sex" value="sex" />
                <entry key="id" value="id" />
            </map>
        </property>
    </bean>


    <bean class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close"
        id="dataSource"
        p:driverClass="${db.auth.driver}"
        p:username="${db.auth.username}"
        p:password="${db.auth.password}"
        p:jdbcUrl="${db.auth.url}"
        p:idleConnectionTestPeriod="${db.idleConnectionTestPeriod}"
        p:idleMaxAgeInMinutes="${db.idleMaxAge}"
        p:maxConnectionsPerPartition="${db.maxConnectionsPerPartition:50}"
        p:minConnectionsPerPartition="${db.minConnectionsPerPartition:10}"
        p:partitionCount="${db.partitionCount:2}"
        p:acquireIncrement="${db.acquireIncrement:2}"
        p:statementsCacheSize="${db.statementsCacheSize:0}"
         />

   <!-- JPA -->
    <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager"
        p:entityManagerFactory-ref="entityManagerFactory" />

    <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory"
        p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaVendorAdapter">
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">${db.auth.dialect}</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.jdbc.batch_size">${db.auth.batchSize:1}</prop>
            </props>
        </property>
    </bean>

    <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
        id="jpaVendorAdapter"
        p:generateDdl="true"
        p:showSql="true" />
      
    <tx:annotation-driven transaction-manager="transactionManager" />
    <context:spring-configured />
    <context:annotation-config />
    <!--
    Injects EntityManager/Factory instances into beans with
    @PersistenceUnit and @PersistenceContext
    -->
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
      
    <!-- 
    Sample, in-memory data store for the ServiceRegistry. A real implementation
    would probably want to replace this with the JPA-backed ServiceRegistry DAO
    The name of this bean should remain "serviceRegistryDao".
    +-->
    <bean id="serviceRegistryDao" class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl"
            p:registeredServices-ref="registeredServicesList" />
    <util:list id="registeredServicesList">
        <bean class="org.jasig.cas.services.RegexRegisteredService"
              p:id="0" p:name="HTTP and IMAP" p:description="Allows HTTP(S) and IMAP(S) protocols"
              p:serviceId="^(https?|imaps?)://.*" p:evaluationOrder="10000001" />
        <!--
        Use the following definition instead of the above to further restrict access
        to services within your domain (including sub domains).
        Note that example.com must be replaced with the domain you wish to permit.
        This example also demonstrates the configuration of an attribute filter
        that only allows for attributes whose length is 3.
        -->
        <!--
        <bean class="org.jasig.cas.services.RegexRegisteredService">
            <property name="id" value="1" />
            <property name="name" value="HTTP and IMAP on example.com" />
            <property name="description" value="Allows HTTP(S) and IMAP(S) protocols on example.com" />
            <property name="serviceId" value="^(https?|imaps?)://([A-Za-z0-9_-]+\.)*example\.com/.*" />
            <property name="evaluationOrder" value="0" />
            <property name="attributeFilter">
              <bean class="org.jasig.cas.services.support.RegisteredServiceRegexAttributeFilter" c:regex="^\w{3}$" /> 
            </property>
        </bean>
        -->
    </util:list>
    
     <!-- JPA -->
<!--     <bean id="serviceRegistryDao" class="org.jasig.cas.services.JpaServiceRegistryDaoImpl" p:entityManagerFactory-ref="entityManagerFactory"/> -->
    
    
    <bean id="auditTrailManager" class="com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager" />
    
    <bean id="healthCheckMonitor" class="org.jasig.cas.monitor.HealthCheckMonitor" p:monitors-ref="monitorsList" />
  
    <util:list id="monitorsList">
      <bean class="org.jasig.cas.monitor.MemoryMonitor" p:freeMemoryWarnThreshold="10" />
      <!--
        NOTE
        The following ticket registries support SessionMonitor:
          * DefaultTicketRegistry
          * JpaTicketRegistry
        Remove this monitor if you use an unsupported registry.
      -->
      <bean class="org.jasig.cas.monitor.SessionMonitor"
          p:ticketRegistry-ref="ticketRegistry"
          p:serviceTicketCountWarnThreshold="5000"
          p:sessionCountWarnThreshold="100000" />
    </util:list>
</beans>

完整示例下载路径 :http://yunpan.cn/cKaRJkyxQGrgy (提取码:4b31)

依赖包common-env源码:http://git.oschina.net/strivezxq/common/tree/master/common-env


用maven的jetty:run 启动两个web工程, 

访问: http://localhost:8088 
登录用户上面配置中有, 是 zhouxq, 密码fpx@1234

NOTE: 由于示例配置了mysql数据库,你需要执行项目里scripts下脚本,修改properties里的配置,如果不想用数据库的方式,就把deployerConfigContext.xml配置中的database相关注释掉,打开stub相关的配置

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值