一、前言

之前整理完CAS Server的安装,现在开始做CAS Server的改造

二、语言改造

CAS默认是使用英文的,虽然在界面上可以切换语言,但还是默认成中文的比较好

打开到WEB-INF/cas-servlet.xml,找到bean id="localeResolver",将默认语言改为zh_CN

CAS学习记录2--CAS Server的改造

重启Tomcat,清除浏览器缓存就可以了

CAS学习记录2--CAS Server的改造

三、账号认证方式改造

CAS支持多种认证方式,现在账号认证基本都是用数据库查询,增加这一部分

首先修改pom.xml,增加数据库访问依赖项

 

 
  1. <dependency>

  2. <groupId>mysql</groupId>

  3. <artifactId>mysql-connector-java</artifactId>

  4. <version>5.0.8</version>

  5. </dependency>

  6. <dependency>

  7. <groupId>org.jasig.cas</groupId>

  8. <artifactId>cas-server-support-jdbc</artifactId>

  9. <version>${project.version}</version>

  10. </dependency>

打开WEB-INF/deployerConfigContext.xml,注释掉bean id="primaryAuthenticationHandler",并增加数据库访问的相关bean,连接池用c3p0,内置支持,也试过dbcp,但是有点冲突,应该可以解决,不想花这时间了

 

 

 
  1. <!--

  2. | TODO: Replace this component with one suitable for your enviroment.

  3. |

  4. | This component provides authentication for the kind of credential used in your environment. In most cases

  5. | credential is a username/password pair that lives in a system of record like an LDAP directory.

  6. | The most common authentication handler beans:

  7. |

  8. | * org.jasig.cas.authentication.LdapAuthenticationHandler

  9. | * org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler

  10. | * org.jasig.cas.adaptors.x509.authentication.handler.support.X509CredentialsAuthenticationHandler

  11. | * org.jasig.cas.support.spnego.authentication.handler.support.JCIFSSpnegoAuthenticationHandler

  12. -->

  13. <!--<bean id="primaryAuthenticationHandler"-->

  14. <!--class="org.jasig.cas.authentication.AcceptUsersAuthenticationHandler">-->

  15. <!--<property name="users">-->

  16. <!--<map>-->

  17. <!--<entry key="casuser" value="Mellon"/>-->

  18. <!--</map>-->

  19. <!--</property>-->

  20. <!--</bean>-->

  21. <bean id="primaryAuthenticationHandler" class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">

  22. <property name="dataSource" ref="casDataSource" />

  23. <property name="sql" value="select password from user where lower(login_name) = lower(?)" />

  24. <property name="passwordEncoder" ref="passwordEncoder"/>

  25. </bean>

  26. <bean id="passwordEncoder" class="org.jasig.cas.custome.Md5PasswordEncoder"/>

  27.  
  28. <!-- c3p0连接池配置 -->

  29. <bean id="casDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

  30. <!-- 用户名-->

  31. <property name="user" value="root"/>

  32. <!-- 用户密码-->

  33. <property name="password" value="123456"/>

  34. <property name="driverClass" value="com.mysql.jdbc.Driver"/>

  35. <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8"/>

  36. <!--连接池中保留的最大连接数。默认值: 15 -->

  37. <property name="maxPoolSize" value="50"/>

  38. <!-- 连接池中保留的最小连接数,默认为:3-->

  39. <property name="minPoolSize" value="5"/>

  40. <!-- 初始化连接池中的连接数,取值应在minPoolSize与maxPoolSize之间,默认为3-->

  41. <property name="initialPoolSize" value="5"/>

  42. <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。默认值: 0 -->

  43. <property name="maxIdleTime" value="60"/>

  44. <!-- 当连接池连接耗尽时,客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限期等待。单位毫秒。默认: 0 -->

  45. <property name="checkoutTimeout" value="3000"/>

  46. <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->

  47. <property name="acquireIncrement" value="3"/>

  48. <!--定义在从数据库获取新连接失败后重复尝试的次数。默认值: 30 ;小于等于0表示无限次-->

  49. <property name="acquireRetryAttempts" value="1"/>

  50. <!--重新尝试的时间间隔,默认为:1000毫秒-->

  51. <property name="acquireRetryDelay" value="1000" />

  52. <!--关闭连接时,是否提交未提交的事务,默认为false,即关闭连接,回滚未提交的事务 -->

  53. <property name="autoCommitOnClose" value="false" />

  54. <!--如果为false,则获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常,但是数据源仍有效保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。默认: false-->

  55. <property name="breakAfterAcquireFailure" value="false"/>

  56. <!--每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->

  57. <property name="idleConnectionTestPeriod" value="60"/>

  58. <!--c3p0全局的PreparedStatements缓存的大小。如果maxStatements与maxStatementsPerConnection均为0,则缓存不生效,只要有一个不为0,则语句的缓存就能生效。如果默认值: 0-->

  59. <property name="maxStatements" value="0"/>

  60. <!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。默认值: 0 -->

  61. <property name="maxStatementsPerConnection" value="0"/>

  62. </bean>

这里需增加一个Md5PasswordEncoder的类,如果密码用其他加密方式,也可以参照修改,特别说明的是Maven会检查文件的版权声明,和代码样式,建议复制一个原有类来改,免得又有七七八八的错

 

在cas-server-webapp下新建包org.jasig.cas.custom,包下新建类Md5PasswordEncoder,代码如下:

 

 
  1. /*

  2. * Licensed to Apereo under one or more contributor license

  3. * agreements. See the NOTICE file distributed with this work

  4. * for additional information regarding copyright ownership.

  5. * Apereo licenses this file to you under the Apache License,

  6. * Version 2.0 (the "License"); you may not use this file

  7. * except in compliance with the License. You may obtain a

  8. * copy of the License at the following location:

  9. *

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

  11. *

  12. * Unless required by applicable law or agreed to in writing,

  13. * software distributed under the License is distributed on an

  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY

  15. * KIND, either express or implied. See the License for the

  16. * specific language governing permissions and limitations

  17. * under the License.

  18. */

  19. package org.jasig.cas.custom;

  20.  
  21. import org.apache.commons.codec.digest.DigestUtils;

  22. import org.jasig.cas.authentication.handler.PasswordEncoder;

  23. import java.io.UnsupportedEncodingException;

  24.  
  25. /**

  26. * Default password encoder for the case where no password encoder is needed.

  27. * Encoding results in the same password that was passed in.

  28. *

  29. * @author tsfdez

  30.  
  31. * @since 3.0.0

  32. */

  33. public final class Md5PasswordEncoder implements PasswordEncoder {

  34. // 转MD5的签名**

  35. private static final String MD5_KEY="67hdskj73nhsdf7";

  36. private static final String INPUT_CHARSET = "utf-8";

  37.  
  38. @Override

  39. public String encode(final String password) {

  40. try {

  41. return DigestUtils.md5Hex((MD5_KEY + password + MD5_KEY).getBytes(INPUT_CHARSET));

  42. } catch (final UnsupportedEncodingException e) {

  43. throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + INPUT_CHARSET, e);

  44. }

  45. }

  46. }

重新启动Tomcat,试下用数据库里的账号登录,登录成功

 

CAS学习记录2--CAS Server的改造

四、主题改造

先说个问题,打开CAS页面的时候,浏览器会一直转圈载入,虽说功能也能用

CAS学习记录2--CAS Server的改造

十有八九是直接引用到国外的CSS或者JS了,翻翻页面代码,果然如此,因为网络的关系,国外的软件多少都有这个问题

打开webapp/js/cas.js,这里用了后台加载,看到带google字样估计就有问题了

 

 
  1. var scripts = [ "https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js",

  2. "https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js",

  3. "https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js",

  4. "https://cdn.rawgit.com/cowboy/javascript-debug/master/ba-debug.min.js"];

  5.  
  6. head.ready(document, function() {

  7. head.load(scripts, resourceLoadedSuccessfully);

  8. });

没关系,CAS是支持主题的,换个试试,除了默认主题,还自带一个apereo主题

 

CAS学习记录2--CAS Server的改造

打开WEB-INF/cas.properties,做如下修改

 

 
  1. #cas.themeResolver.defaultThemeName=cas-theme-default

  2. cas.themeResolver.defaultThemeName=apereo

 

重启Tomcat,看看效果

CAS学习记录2--CAS Server的改造

样式变了,也不转圈了,这个主题比起默认主题更加单纯,可以在它基础上修改出自定义的主题样式

公司都有自己的登录页面,可以在WEB-INF/view/jsp/default/ui/casLoginView.jsp里修改,其他页面不用改,一般登录完就跳回原系统了

CAS学习记录2--CAS Server的改造

五、登出改造

登出使用https://localhost:9001/cas/logout这个地址

CAS学习记录2--CAS Server的改造

实际使用中,要求登出后返回到登录界面的,而CAS默认是不支持返回跳转的,这里需要做个修改

打开WEB-INF/cas-servlet.xml,基本上业务逻辑都在这里了,搜索logout,找到这个

 

 
  1. <bean id="logoutAction" class="org.jasig.cas.web.flow.LogoutAction"

  2. p:servicesManager-ref="servicesManager"

  3. p:followServiceRedirects="${cas.logout.followServiceRedirects:false}"/>

配置在属性文件里,打开WEB-INF/cas.properties,默认是false的,改成true,这样就可以加?service的方式跳转了

 
  1. # Specify whether CAS should redirect to the specified service parameter on /logout requests

  2. cas.logout.followServiceRedirects=true

六、验证码改造

这里用google的Kaptcha来实现,可以用servlet方式配置,也可以用spring方式,选用servlet的

首先打开cas-server-webapp的pom.xml文件,增加Kaptcha依赖

 

 
  1. <dependency>

  2. <groupId>com.github.penggle</groupId>

  3. <artifactId>kaptcha</artifactId>

  4. <version>2.3.2</version>

  5. </dependency>

打开WEB-INF/web.xml,增加servlet配置

 

 

 
  1. <!-- 验证码功能 -->

  2. <servlet>

  3. <servlet-name>Kaptcha</servlet-name>

  4. <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>

  5. <init-param>

  6. <param-name>kaptcha.border</param-name>

  7. <param-value>no</param-value>

  8. </init-param>

  9. <init-param>

  10. <param-name>kaptcha.textproducer.char.space</param-name>

  11. <param-value>5</param-value>

  12. </init-param>

  13. <init-param>

  14. <param-name>kaptcha.textproducer.char.length</param-name>

  15. <param-value>5</param-value>

  16. </init-param>

  17. </servlet>

  18. <servlet-mapping>

  19. <servlet-name>Kaptcha</servlet-name>

  20. <url-pattern>/captcha.jpg</url-pattern>

  21. </servlet-mapping>

打开casLoginView.jsp,在password后增加验证码显示

 

 

 
  1. <section class="row">

  2. <label for="captcha"><spring:message code="screen.welcome.label.captcha" /></label>

  3. <spring:message code="screen.welcome.label.captcha.accesskey" var="captchaAccessKey" />

  4. <table>

  5. <tr>

  6. <td>

  7. <form:input cssClass="required" cssErrorClass="error" id="captcha" size="10" tabindex="2" path="captcha" accesskey="${captchaAccessKey}" htmlEscape="true" autocomplete="off" />

  8. </td>

  9. <td style="vertical-align: bottom;">

  10. <img onclick="this.src='captcha.jpg?'+Math.random()" width="93" height="30" src="captcha.jpg">

  11. </td>

  12. </tr>

  13. </table>

  14. </section>

找到语言档messages_zh_CN.properties,在password后增加

 

 
  1. screen.welcome.label.captcha=\u9A8C\u8BC1\u7801:

  2. screen.welcome.label.captcha.accesskey=c

在org.jasig.cas.custom包下新建UsernamePasswordCredentialWithCaptcha.java,代码如下:

 

 

 
  1. /*

  2. * Licensed to Apereo under one or more contributor license

  3. * agreements. See the NOTICE file distributed with this work

  4. * for additional information regarding copyright ownership.

  5. * Apereo licenses this file to you under the Apache License,

  6. * Version 2.0 (the "License"); you may not use this file

  7. * except in compliance with the License. You may obtain a

  8. * copy of the License at the following location:

  9. *

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

  11. *

  12. * Unless required by applicable law or agreed to in writing,

  13. * software distributed under the License is distributed on an

  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY

  15. * KIND, either express or implied. See the License for the

  16. * specific language governing permissions and limitations

  17. * under the License.

  18. */

  19. package org.jasig.cas.custom;

  20.  
  21. import org.apache.commons.lang3.builder.HashCodeBuilder;

  22. import org.jasig.cas.authentication.UsernamePasswordCredential;

  23.  
  24. import javax.validation.constraints.NotNull;

  25. import javax.validation.constraints.Size;

  26.  
  27. /**

  28. * 带验证码的登录界面.

  29. *

  30. * @author tsfdez

  31. * @since 3.0.0

  32. */

  33. public class UsernamePasswordCredentialWithCaptcha extends UsernamePasswordCredential {

  34.  
  35. /**

  36. * 验证码.

  37. */

  38. @NotNull

  39. @Size(min = 1, message = "captcha.required")

  40. private String captcha;

  41.  
  42. public String getCaptcha() {

  43. return captcha;

  44. }

  45.  
  46. public void setCaptcha(final String captcha) {

  47. this.captcha = captcha;

  48. }

  49.  
  50. /**

  51. * {@inheritDoc}

  52. */

  53. @Override

  54. public boolean equals(final Object o) {

  55. if (this == o) {

  56. return true;

  57. }

  58. if (o == null || getClass() != o.getClass()) {

  59. return false;

  60. }

  61.  
  62. final UsernamePasswordCredentialWithAuthCode that = (UsernamePasswordCredentialWithAuthCode) o;

  63.  
  64. if (getPassword() != null ? !getPassword().equals(that.getPassword())

  65. : that.getPassword() != null) {

  66. return false;

  67. }

  68.  
  69. if (getPassword() != null ? !getPassword().equals(that.getPassword())

  70. : that.getPassword() != null) {

  71. return false;

  72. }

  73. if (captcha != null ? !captcha.equals(that.captcha)

  74. : that.captcha != null) {

  75. return false;

  76. }

  77. return true;

  78. }

  79.  
  80. @Override

  81. public int hashCode() {

  82. return new HashCodeBuilder().append(getUsername())

  83. .append(getPassword()).append(captcha).toHashCode();

  84. }

  85. }

打开WEB-INF/webflow/login/login-webflow.xml,修改设定

 

 

 
  1. <!--<var name="credential" class="org.jasig.cas.authentication.UsernamePasswordCredential"/>-->

  2. <var name="credential" class="org.jasig.cas.custom.UsernamePasswordCredentialWithCaptcha"/>

好了,重启一下Tomcat,看看效果,有显示验证码,但是没有效果,还需继续修改

 

CAS学习记录2--CAS Server的改造

在org.jasig.cas.custom包下新建AuthenticationViaFormActionWithCaptcha.java,代码如下:

 

 
  1. /*

  2. * Licensed to Apereo under one or more contributor license

  3. * agreements. See the NOTICE file distributed with this work

  4. * for additional information regarding copyright ownership.

  5. * Apereo licenses this file to you under the Apache License,

  6. * Version 2.0 (the "License"); you may not use this file

  7. * except in compliance with the License. You may obtain a

  8. * copy of the License at the following location:

  9. *

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

  11. *

  12. * Unless required by applicable law or agreed to in writing,

  13. * software distributed under the License is distributed on an

  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY

  15. * KIND, either express or implied. See the License for the

  16. * specific language governing permissions and limitations

  17. * under the License.

  18. */

  19. package org.jasig.cas.custom;

  20.  
  21. import javax.servlet.http.HttpServletRequest;

  22. import javax.servlet.http.HttpSession;

  23.  
  24. import org.apache.commons.lang3.StringUtils;

  25. import org.jasig.cas.authentication.Credential;

  26. import org.jasig.cas.web.flow.AuthenticationViaFormAction;

  27. import org.jasig.cas.web.support.WebUtils;

  28. import org.springframework.binding.message.MessageBuilder;

  29. import org.springframework.binding.message.MessageContext;

  30. import org.springframework.webflow.execution.Event;

  31. import org.springframework.webflow.execution.RequestContext;

  32.  
  33. /**

  34. * 验证码校验类.

  35. *

  36. * @author tsfdez

  37. * @since 3.0.0

  38. */

  39. public class AuthenticationViaFormActionWithCaptcha extends AuthenticationViaFormAction {

  40.  
  41. /**

  42. * 验证码校验.

  43. * @param context context

  44. * @param credentials credentials

  45. * @param messageContext messageContext

  46. * @return the resulting event.

  47. * @since 3.0.0

  48. */

  49. public final Event validatorCode(final RequestContext context, final Credential credentials,

  50. final MessageContext messageContext) {

  51. final HttpServletRequest request = WebUtils.getHttpServletRequest(context);

  52. final HttpSession session = request.getSession();

  53. final String captcha = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

  54. session.removeAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

  55.  
  56. final UsernamePasswordCredentialWithCaptcha upc = (UsernamePasswordCredentialWithCaptcha) credentials;

  57. final String submitCaptcha = upc.getCaptcha();

  58.  
  59. if (StringUtils.isEmpty(submitCaptcha) || StringUtils.isEmpty(captcha)) {

  60. messageContext.addMessage(new MessageBuilder().error().code("captcha.required").build());

  61. return new Event(this, ERROR);

  62. }

  63. if (submitCaptcha.equals(captcha)) {

  64. return new Event(this, SUCCESS);

  65. }

  66. messageContext.addMessage(new MessageBuilder().error().code("error.authentication.captcha.bad").build());

  67. return new Event(this, ERROR);

  68. }

  69. }

找到语言档messages_zh_CN.properties,在password.required后增加

 

 

 
  1. error.invalid.loginticket=\u60a8\u4e0d\u80fd\u591f\u518d\u6b21\u63d0\u4ea4\u5df2\u7ecf\u63d0\u4ea4\u8fc7\u7684\u8868\u5355\u3002

  2. username.required=\u5fc5\u987b\u5f55\u5165\u7528\u6237\u540d\u3002

  3. password.required=\u5fc5\u987b\u5f55\u5165\u5bc6\u7801\u3002

  4. captcha.required=\u5fc5\u987b\u5f55\u5165\u9a8c\u8bc1\u7801\u3002

  5. error.authentication.captcha.bad=\u5f55\u5165\u9a8c\u8bc1\u7801\u4e0d\u6b63\u786e\u3002

打开WEB-INF/webflow/login/login-webflow.xml,修改设定viewLoginForm,同时增加设定captchaValidate

 

 

 
  1. <view-state id="viewLoginForm" view="casLoginView" model="credential">

  2. <binder>

  3. <binding property="username" required="true"/>

  4. <binding property="password" required="true"/>

  5. <binding property="captcha" required="true"/>

  6. </binder>

  7. <on-entry>

  8. <set name="viewScope.commandName" value="'credential'"/>

  9.  
  10. <!--

  11. <evaluate expression="samlMetadataUIParserAction" />

  12. -->

  13. </on-entry>

  14. <transition on="submit" bind="true" validate="true" to="captchaValidate"/>

  15. </view-state>

  16.  
  17. <action-state id="captchaValidate">

  18. <evaluate expression="authenticationViaFormAction.validatorCode(flowRequestContext, flowScope.credential, messageContext)" />

  19. <transition on="error" to="generateLoginTicket" />

  20. <transition on="success" to="realSubmit" />

  21. </action-state>

重启一下Tomcat,看看效果

 

CAS学习记录2--CAS Server的改造

七、小结

Server端的改造完成了,后面开始Client端的设置

转载:https://blog.csdn.net/tsfdez/article/details/75663306

相关文章:

  • 2021-09-12
  • 2022-12-23
  • 2021-08-19
  • 2022-01-04
  • 2021-08-01
  • 2021-06-22
  • 2021-12-30
猜你喜欢
  • 2021-05-01
  • 2021-08-11
  • 2021-07-09
  • 2022-01-05
  • 2021-08-13
  • 2022-12-23
相关资源
相似解决方案