CAS 入门实战(3)--客户端接入
本文主要介绍 CAS 客户端的接入,使用到的软件版本:JDK 1.8.0_191、Tomcat 8.5.76、SpringBoot 2.5.11、CAS 5.3.16、CAS Client 3.6.4。
1、服务端准备
这里假设服务端已经安装完毕,地址为:http://127.0.0.1:8080/cas,服务端的安装方法可参考:CAS 入门实战(2)--服务端安装。
2、普通 Java Web 应用接入
这里客户端的应用地址为:http://127.0.0.1:9090/cas-client。
2.1、引入依赖
<dependency> <groupId>org.jasig.cas.client</groupId> <artifactId>cas-client-core</artifactId> <version>3.6.4</version> </dependency>
如果不是使用 maven 来构建项目,可以手动下载对应的包后放到应用的 lib 下。
2.2、配置 AuthenticationFilter
该类型过滤器用于检测用户是否需要进行身份验证;如果需要,则会将用户重定向到 CAS 服务器。有两个可选的过滤器:
org.jasig.cas.client.authentication.AuthenticationFilter
org.jasig.cas.client.authentication.Saml11AuthenticationFilter
这里使用 org.jasig.cas.client.authentication.AuthenticationFilter,在 web.xml 增加如下配置:
<filter> <filter-name>CAS Authentication Filter</filter-name> <filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class> <init-param> <param-name>casServerUrlPrefix</param-name> <param-value>http://127.0.0.1:8080/cas</param-value> </init-param> <init-param> <param-name>serverName</param-name> <param-value>http://127.0.0.1:9090</param-value> </init-param> </filter> <filter-mapping> <filter-name>CAS Authentication Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
org.jasig.cas.client.authentication.AuthenticationFilter 过滤器的参数说明如下:
Property | Description | Required |
---|---|---|
casServerUrlPrefix |
The start of the CAS server URL, i.e. https://localhost:8443/cas |
Yes (unless casServerLoginUrl is set) |
casServerLoginUrl |
Defines the location of the CAS server login URL, i.e. https://localhost:8443/cas/login . This overrides casServerUrlPrefix , if set. |
Yes (unless casServerUrlPrefix is set) |
serverName |
The name of the server this application is hosted on. Service URL will be dynamically constructed using this, i.e. https://localhost:8443 (you must include the protocol, but port is optional if it's a standard port). | Yes |
service |
The service URL to send to the CAS server, i.e. https://localhost:8443/yourwebapp/index.html |
No |
renew |
specifies whether renew=true should be sent to the CAS server. Valid values are either true/false (or no value at all). Note that renew cannot be specified as local init-param setting. |
No |
gateway |
specifies whether gateway=true should be sent to the CAS server. Valid values are either true/false (or no value at all) |
No |
artifactParameterName |
specifies the name of the request parameter on where to find the artifact (i.e. ticket ). |
No |
serviceParameterName |
specifies the name of the request parameter on where to find the service (i.e. service ) |
No |
encodeServiceUrl |
Whether the client should auto encode the service url. Defaults to true |
No |
ignorePattern |
Defines the url pattern to ignore, when intercepting authentication requests. | No |
ignoreUrlPatternType |
Defines the type of the pattern specified. Defaults to REGEX . Other types are CONTAINS , EXACT , FULL_REGEX . Can also accept a fully-qualified class name that implements UrlPatternMatcherStrategy . |
No |
gatewayStorageClass |
The storage class used to record gateway requests | No |
authenticationRedirectStrategyClass |
The class name of the component to decide how to handle authn redirects to CAS | No |
method |
The method used by the CAS server to send the user back to the application. Defaults to null |
No |
ignoreUrlPatternType 支持的类型说明如下:
Type | Description |
---|---|
REGEX |
Matches the URL the ignorePattern using Matcher#find() . It matches the next occurrence within the substring that matches the regex. |
CONTAINS |
Uses the String#contains() operation to determine if the url contains the specified pattern. Behavior is case-sensitive. |
EXACT |
Uses the String#equals() operation to determine if the url exactly equals the specified pattern. Behavior is case-sensitive. |
FULL_REGEX |
Matches the URL the ignorePattern using Matcher#matches() . It matches the expression against the entire string as it implicitly add a ^ at the start and $ at the end of the pattern, so it will not match substring or part of the string. ^ and $ are meta characters that represents start of the string and end of the string respectively. |
2.3、配置 TicketValidationFilter
该类型过滤器负责对票据进行验证。有多个可选的过滤器:
org.jasig.cas.client.validation.Cas10TicketValidationFilter
org.jasig.cas.client.validation.Saml11TicketValidationFilter
org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter
org.jasig.cas.client.validation.Cas30ProxyReceivingTicketValidationFilter
org.jasig.cas.client.validation.json.Cas30JsonProxyReceivingTicketValidationFilter
这里使用 org.jasig.cas.client.validation.Cas30ProxyReceivingTicketValidationFilter,在 web.xml 增加如下配置:
<filter> <filter-name>CAS Validation Filter</filter-name> <filter-class>org.jasig.cas.client.validation.Cas30ProxyReceivingTicketValidationFilter</filter-class> <init-param> <param-name>casServerUrlPrefix</param-name> <param-value>http://127.0.0.1:8080/cas</param-value> </init-param> <init-param> <param-name>serverName</param-name> <param-value>http://127.0.0.1:9090</param-value> </init-param> </filter> <filter-mapping> <filter-name>CAS Validation Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
org.jasig.cas.client.validation.Cas30ProxyReceivingTicketValidationFilter 过滤器的参数说明如下:
Property | Description | Required |
---|---|---|
casServerUrlPrefix |
The start of the CAS server URL, i.e. https://localhost:8443/cas |
Yes |
serverName |
The name of the server this application is hosted on. Service URL will be dynamically constructed using this, i.e. https://localhost:8443 (you must include the protocol, but port is optional if it's a standard port). |
Yes |
renew |
Specifies whether renew=true should be sent to the CAS server. Valid values are either true/false (or no value at all). Note that renew cannot be specified as local init-param setting. |
No |
redirectAfterValidation |
Whether to redirect to the same URL after ticket validation, but without the ticket in the parameter. Defaults to true . |
No |
useSession |
Whether to store the Assertion in session or not. If sessions are not used, tickets will be required for each request. Defaults to true . |
No |
exceptionOnValidationFailure |
whether to throw an exception or not on ticket validation failure. Defaults to true |
No |
proxyReceptorUrl |
The URL to watch for PGTIOU/PGT responses from the CAS server. Should be defined from the root of the context. For example, if your application is deployed in /cas-client-app and you want the proxy receptor URL to be /cas-client-app/my/receptor you need to configure proxyReceptorUrl to be /my/receptor . |
No |
acceptAnyProxy |
Specifies whether any proxy is OK. Defaults to false . |
No |
allowedProxyChains |
Specifies the proxy chain. Each acceptable proxy chain should include a space-separated list of URLs (for exact match) or regular expressions of URLs (starting by the ^ character). Each acceptable proxy chain should appear on its own line. |
No |
proxyCallbackUrl |
The callback URL to provide the CAS server to accept Proxy Granting Tickets. | No |
proxyGrantingTicketStorageClass |
Specify an implementation of the ProxyGrantingTicketStorage class that has a no-arg constructor. | No |
sslConfigFile |
A reference to a properties file that includes SSL settings for client-side SSL config, used during back-channel calls. The configuration includes keys for protocol which defaults to SSL , keyStoreType , keyStorePath , keyStorePass , keyManagerType which defaults to SunX509 and certificatePassword . |
No. |
encoding |
Specifies the encoding charset the client should use | No |
secretKey |
The secret key used by the proxyGrantingTicketStorageClass if it supports encryption. |
No |
cipherAlgorithm |
The algorithm used by the proxyGrantingTicketStorageClass if it supports encryption. Defaults to DESede |
No |
millisBetweenCleanUps |
Startup delay for the cleanup task to remove expired tickets from the storage. Defaults to 60000 msec |
No |
ticketValidatorClass |
Ticket validator class to use/create | No |
hostnameVerifier |
Hostname verifier class name, used when making back-channel calls | No |
privateKeyPath |
The path to a private key to decrypt PGTs directly sent encrypted as an attribute | No |
privateKeyAlgorithm |
The algorithm of the private key. Defaults to RSA |
No |
如果设置了 acceptAnyProxy 或 allowedProxyChains 参数,则会创建 Cas30ProxyTicketValidator;否则创建不支持代理票据的 Cas30ServiceTicketValidator。
2.4、配置 HttpServletRequestWrapperFilter(可选)
包装 HttpServletRequest 的过滤器,getRemoteUser 和 getPrincipal 方法会返回与 CAS 相关的实体信息。在 web.xml 增加如下配置:
<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>
该过滤器的参数说明如下:
Property | Description | Required |
---|---|---|
roleAttribute |
Used to determine the principal role. | No |
ignoreCase |
Whether role checking should ignore case. Defaults to false |
No |
2.5、配置 AssertionThreadLocalFilter(可选)
该过滤器把登录信息放入 ThreadLocal 中,可以通过 org.jasig.cas.client.util.AssertionHolder 来获取用户信息(AssertionHolder.getPrincipal()),这在无法使用 HttpServletRequest 时很有用。在 web.xml 增加如下配置:
<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>
2.6、配置 ErrorRedirectFilter(可选)
该过滤器用于发生异常时,重定向到指定的地址。在 web.xml 增加如下配置:
<filter> <filter-name>CAS Error Redirect Filter</filter-name> <filter-class>org.jasig.cas.client.util.ErrorRedirectFilter</filter-class> <init-param> <param-name>java.lang.Exception</param-name> <param-value>/yourapp/error.jsp</param-value> </init-param> <init-param> <param-name>defaultErrorRedirectPage</param-name> <param-value>/yourapp/defaulterror.jsp</param-value> </init-param> </filter> <filter-mapping> <filter-name>CAS Error Redirect Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
该过滤器的参数说明如下:
Property | Description | Required |
---|---|---|
defaultErrorRedirectPage |
Default url to redirect to, in case no error matches are found. | Yes |
java.lang.Exception |
Fully qualified exception name. Its value must be redirection url | No |
2.7、单点登出(可选)
2.7.1、单点登录服务端配置
在 WEB-INF\classes\application.properties 文件,增加如下配置:
#允许登出后跳转到指定页面 cas.logout.followServiceRedirects=true #登出后重定向地址的参数名 cas.logout.redirectParameter=service #登出后默认的重定向地址 #cas.logout.redirectUrl=http://127.0.0.1:9090 #登出时是否弹出确认框 cas.logout.confirmLogout=false #是否移除子系统的票据 cas.logout.removeDescendantTickets=true #是否禁用单点登出 #cas.slo.disabled=true #是否默认异步通知客户端清除session cas.slo.asynchronous=false
2.7.2、单点登录客户端配置
单点登出客户端需要配置一个 SingleSignOutFilter 和一个 ContextListener,SingleSignOutFilter 需要配置在其他过滤器的最前面。在 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> <init-param> <param-name>logoutCallbackPath</param-name> <param-value>http://127.0.0.1:9090/cas_client_tomcat_war_exploded/test.jsp</param-value> </init-param> </filter> <filter-mapping> <filter-name>CAS Single Sign Out Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
SingleSignOutFilter 过滤器的参数说明如下:
Property | Description | Required |
---|---|---|
artifactParameterName |
The ticket artifact parameter name. Defaults to ticket |
No |
logoutParameterName |
Defaults to logoutRequest |
No |
relayStateParameterName |
Defaults to RelayState |
No |
eagerlyCreateSessions |
Defaults to true |
No |
artifactParameterOverPost |
Defaults to false |
No |
logoutCallbackPath |
The path which is expected to receive logout callback requests from the CAS server. This is necessary if your app needs access to the raw input stream when handling form posts. If not configured, the default behavior will check every form post for a logout parameter. | No |
2.8、编写测试页面
这里写个简单的 JSP,在页面中获取用户的信息(web.xml 中需配置 HttpServletRequestWrapperFilter 和 单点登出):
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page import="org.jasig.cas.client.authentication.AttributePrincipal"%> <% String remoteUser = request.getRemoteUser(); AttributePrincipal principal = (AttributePrincipal)request.getUserPrincipal(); String attributes = principal.getAttributes().toString(); %> <html> <head> <title>Title</title> </head> <body> remoteUser:<%=remoteUser%> principalName:<%=principal.getName()%> principalAttributes:<%=attributes%> <br><a href="http://127.0.0.1:8080/cas/logout?service=http://127.0.0.1:9090/cas-client/index.jsp">logout</a> </body> </html>
2.9、部署 Web 应用
部署 Web 应用到 Java Web 应用服务器(如:Tomcat)中即可。
3、SpringBoot 应用接入
3.1、引入依赖
<dependency> <groupId>org.jasig.cas.client</groupId> <artifactId>cas-client-support-springboot</artifactId> <version>3.6.4</version> </dependency>
3.2、增加 CAS 相关配置
在 application.yml 中增加如下配置:
cas: server-login-url: http://127.0.0.1:8080/cas/login #cas服务端登录地址 server-url-prefix: http://127.0.0.1:8080/cas #cas服务端地址 client-host-url: http://127.0.0.1:9090 #客户端地址 validation-type: cas3 #验证使用的协议 server: port: 9090
其他的可选参数如下:
cas.single-logout.enabled 是否单点登出,默认false
cas.authentication-url-patterns 与AuthenticationFilter作用类似,默认/*
cas.validation-url-patterns 与TicketValidationFilter作用类似,默认/*
cas.request-wrapper-url-patterns 与HttpServletRequestWrapperFilter作用类似,默认/*
cas.assertion-thread-local-url-patterns
cas.gateway
cas.use-session
cas.attribute-authorities
cas.redirect-after-validation
cas.allowed-proxy-chains
cas.proxy-callback-url
cas.proxy-receptor-url
cas.accept-any-proxy
server.context-parameters.renew
3.3、启动类增加 @EnableCasClient
@EnableCasClient @SpringBootApplicationpublic class CasApplication {...}
3.4、编写测试 Controller
package com.abc.controller; import org.jasig.cas.client.authentication.AttributePrincipal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; @RequestMapping("/test") @Controller public class TestController { private static Logger logger = LoggerFactory.getLogger(TestController.class); @ResponseBody @RequestMapping("/getUser") public String test1(HttpServletRequest request) { String remoteUser = request.getRemoteUser(); AttributePrincipal principal = (AttributePrincipal)request.getUserPrincipal(); return "remoteUser=" + remoteUser + ",principalName=" + principal.getName() + ",principalAttributes=" + principal.getAttributes(); } }
启动应用后访问:http://127.0.0.1:9090/test/getUser,登录后页面返回用户相关信息。
4、CAS 客户端集群接入
如果客户端是集群的话,可以使用 Spring Session 来实现同一类型的各客户端节点的 Session 共享;前端使用代理服务器来代理。
4.1、集群创建
Spring Session 的使用可参考:https://www.cnblogs.com/wuyongyin/p/11775849.html,这里就不详述了。假设使用上面的 SpringBoot 应用来组建集群:
地址 | 说明 |
http://127.0.0.1:9090 | 节点1 |
http://127.0.0.1:9091 | 节点2 |
http://127.0.0.1:9092 | 代理地址 |
启动节点1:
java -Dcas.client-host-url=http://127.0.0.1:9092 -Dserver.port=9090 -jar cas-client-springboot-1.0.0.jar
启动节点2
java -Dcas.client-host-url=http://127.0.0.1:9092 -Dserver.port=9091 -jar cas-client-springboot-1.0.0.jar
配置 nginx 代理:
upstream cas { server 127.0.0.1:9090 weight=1; server 127.0.0.1:9091 weight=1; #ip_hash; } server { listen 9092; server_name localhost; location / { proxy_pass http://cas; } }
启动 ngxin 并访问代理地址:http://127.0.0.1:9092/test/getUser。
4.2、集群单点登出
使用 Spring Session 后,单点登出客户端的 Session 还是存在的,可能是 CAS 客户端还不能和 Spring Session 结合使用。处理方法:
1、先调用客户端的一个请求,在该请求中使用 Session 失效:
@ResponseBody @RequestMapping("/logout") public String logout(HttpSession session) { session.invalidate(); return "logout success"; }
2、再访问单点登出的地址 http://127.0.0.1:8080/cas/logout?service=http://127.0.0.1:9092/test/getUser。
CAS 客户端接入的详细说明可参考官网:https://github.com/apereo/java-cas-client。