CAS 认证
概述
JA-SIG 开发了一个企业级的单点登录系统,名为 CAS。与其他方案不同,JA-SIG 的中央认证服务是开源的、广泛使用的、易于理解的、平台独立的,并且支持代理功能。Spring Security 完全支持 CAS,并为从 Spring Security 的单应用部署到由企业级 CAS 服务器保护的多应用部署提供了简单的迁移路径。
您可以在 www.apereo.org 了解更多关于 CAS 的信息。您还需要访问此网站下载 CAS 服务器文件。
CAS 工作原理
虽然 CAS 网站上详细介绍了 CAS 的架构,但我们在此处 Spring Security 的上下文中再次提供一般概述。Spring Security 3.x 支持 CAS 3。在撰写本文时,CAS 服务器版本为 3.4。
在您的企业中,您需要设置一个 CAS 服务器。CAS 服务器只是一个标准的 WAR 文件,因此设置您的服务器并不困难。在 WAR 文件内部,您将自定义显示给用户的登录和其他单点登录页面。
部署 CAS 3.4 服务器时,您还需要在 CAS 附带的 deployerConfigContext.xml 中指定一个 AuthenticationHandler。AuthenticationHandler 有一个简单的方法,它返回一个布尔值,指示给定的一组凭据是否有效。您的 AuthenticationHandler 实现需要链接到某种后端认证存储库,例如 LDAP 服务器或数据库。CAS 本身开箱即用提供了许多 AuthenticationHandler 来协助完成此任务。当您下载并部署服务器 WAR 文件时,它已设置为成功验证输入与其用户名匹配的密码的用户,这对于测试很有用。
除了 CAS 服务器本身,其他关键参与者当然是部署在您企业中的安全 Web 应用程序。这些 Web 应用程序被称为“服务”。服务有三种类型。验证服务票据的服务,可以获取代理票据的服务,以及验证代理票据的服务。验证代理票据有所不同,因为必须验证代理列表,而且代理票据通常可以重复使用。
Spring Security 和 CAS 交互序列
Web 浏览器、CAS 服务器和 Spring Security 保护的服务之间的基本交互如下
-
Web 用户正在浏览服务的公共页面。CAS 或 Spring Security 不涉及其中。
-
用户最终请求一个安全页面或其使用的某个 bean 是安全的。Spring Security 的
ExceptionTranslationFilter将检测到AccessDeniedException或AuthenticationException。 -
由于用户的
Authentication对象(或缺乏此对象)导致了AuthenticationException,ExceptionTranslationFilter将调用配置的AuthenticationEntryPoint。如果使用 CAS,这将是CasAuthenticationEntryPoint类。 -
CasAuthenticationEntryPoint将把用户的浏览器重定向到 CAS 服务器。它还将指示一个service参数,这是 Spring Security 服务(您的应用程序)的回调 URL。例如,浏览器被重定向到的 URL 可能是 my.company.com/cas/login?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Flogin/cas。 -
用户浏览器重定向到 CAS 后,系统会提示他们输入用户名和密码。如果用户提供了一个会话 Cookie,表明他们之前已登录,则不会再次提示他们登录(此过程有一个例外,我们稍后会讨论)。CAS 将使用上面讨论的
PasswordHandler(如果使用 CAS 3.0,则为AuthenticationHandler)来决定用户名和密码是否有效。 -
成功登录后,CAS 会将用户的浏览器重定向回原始服务。它还会包含一个
ticket参数,这是一个代表“服务票据”的不透明字符串。继续我们之前的示例,浏览器重定向到的 URL 可能是 server3.company.com/webapp/login/cas?ticket=ST-0-ER94xMJmn6pha35CQRoZ。 -
回到服务 Web 应用程序中,
CasAuthenticationFilter始终侦听对/login/cas的请求(这是可配置的,但在本介绍中我们将使用默认值)。处理过滤器将构造一个表示服务票据的UsernamePasswordAuthenticationToken。主体将等于CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER,而凭据将是服务票据的不透明值。然后,此身份验证请求将交给配置的AuthenticationManager。 -
AuthenticationManager实现将是ProviderManager,它又配置了CasAuthenticationProvider。CasAuthenticationProvider仅响应包含 CAS 特定主体(例如CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER)的UsernamePasswordAuthenticationToken和CasAuthenticationToken(稍后讨论)。 -
CasAuthenticationProvider将使用TicketValidator实现来验证服务票据。这通常是Cas20ServiceTicketValidator,它是 CAS 客户端库中包含的类之一。如果应用程序需要验证代理票据,则使用Cas20ProxyTicketValidator。TicketValidator向 CAS 服务器发出 HTTPS 请求以验证服务票据。它可能还包含一个代理回调 URL,此示例中包含了该 URL:my.company.com/cas/proxyValidate?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Flogin/cas&ticket=ST-0-ER94xMJmn6pha35CQRoZ&pgtUrl=https://server3.company.com/webapp/login/cas/proxyreceptor。 -
回到 CAS 服务器端,验证请求将被接收。如果提交的服务票据与票据发往的服务 URL 匹配,CAS 将以 XML 形式提供肯定响应,指示用户名。如果身份验证中涉及任何代理(如下所述),代理列表也包含在 XML 响应中。
-
[可选] 如果对 CAS 验证服务的请求中包含代理回调 URL(在
pgtUrl参数中),CAS 将在 XML 响应中包含一个pgtIou字符串。此pgtIou代表一个代理授予票据借据。CAS 服务器将创建自己的 HTTPS 连接返回到pgtUrl。这是为了相互验证 CAS 服务器和声明的服务 URL。HTTPS 连接将用于将代理授予票据发送到原始 Web 应用程序。例如,server3.company.com/webapp/login/cas/proxyreceptor?pgtIou=PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt&pgtId=PGT-1-si9YkkHLrtACBo64rmsi3v2nf7cpCResXg5MpESZFArbaZiOKH。 -
Cas20TicketValidator将解析从 CAS 服务器收到的 XML。它将向CasAuthenticationProvider返回一个TicketResponse,其中包括用户名(必需)、代理列表(如果涉及任何代理)和代理授予票据借据(如果请求了代理回调)。 -
接下来,
CasAuthenticationProvider将调用一个已配置的CasProxyDecider。CasProxyDecider指示TicketResponse中的代理列表是否可被服务接受。Spring Security 提供了几种实现:RejectProxyTickets、AcceptAnyCasProxy和NamedCasProxyDecider。这些名称大部分都具有自解释性,除了NamedCasProxyDecider,它允许提供一个受信任代理的List。 -
CasAuthenticationProvider接下来将请求AuthenticationUserDetailsService加载适用于Assertion中包含的用户的GrantedAuthority对象。 -
如果没有问题,
CasAuthenticationProvider会构造一个CasAuthenticationToken,其中包含TicketResponse中包含的详细信息和一组至少包含FACTOR_BEARER的GrantedAuthority。 -
控制权随后返回给
CasAuthenticationFilter,后者将创建的CasAuthenticationToken放置在安全上下文中。 -
用户的浏览器被重定向到导致
AuthenticationException的原始页面(或根据配置自定义目标)。
很高兴你还在!现在让我们看看如何配置它
CAS 客户端配置
由于 Spring Security,CAS 的 Web 应用程序端变得很容易。假设您已经了解使用 Spring Security 的基础知识,因此此处不再赘述。我们将假设正在使用基于命名空间的配置,并根据需要添加 CAS bean。每个部分都建立在前一个部分的基础上。Spring Security 示例中可以找到完整的 CAS 示例应用程序。
服务票据认证
本节描述如何设置 Spring Security 以验证服务票据。通常,Web 应用程序只需要这样做。您需要在应用程序上下文中添加一个 ServiceProperties bean。这表示您的 CAS 服务
<bean id="serviceProperties"
class="org.springframework.security.cas.ServiceProperties">
<property name="service"
value="https://:8443/cas-sample/login/cas"/>
<property name="sendRenew" value="false"/>
</bean>
service 必须等于一个由 CasAuthenticationFilter 监控的 URL。sendRenew 默认为 false,但如果您的应用程序特别敏感,则应将其设置为 true。此参数的作用是告知 CAS 登录服务单点登录不可接受。相反,用户需要重新输入其用户名和密码才能获得对服务的访问权限。
应配置以下 bean 以启动 CAS 身份验证过程(假设您正在使用命名空间配置)
<security:http entry-point-ref="casEntryPoint">
...
<security:custom-filter position="CAS_FILTER" ref="casFilter" />
</security:http>
<bean id="casFilter"
class="org.springframework.security.cas.web.CasAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"/>
</bean>
<bean id="casEntryPoint"
class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
<property name="loginUrl" value="https://:9443/cas/login"/>
<property name="serviceProperties" ref="serviceProperties"/>
</bean>
为了使 CAS 正常运行,ExceptionTranslationFilter 的 authenticationEntryPoint 属性必须设置为 CasAuthenticationEntryPoint bean。这可以通过使用 entry-point-ref 轻松完成,如上例所示。CasAuthenticationEntryPoint 必须引用 ServiceProperties bean(如上所述),该 bean 提供企业 CAS 登录服务器的 URL。用户的浏览器将重定向到此处。
CasAuthenticationFilter 与 UsernamePasswordAuthenticationFilter(用于基于表单的登录)具有非常相似的属性。您可以使用这些属性来自定义诸如认证成功和失败的行为。
接下来你需要添加一个 CasAuthenticationProvider 及其协作者
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="casAuthenticationProvider" />
</security:authentication-manager>
<bean id="casAuthenticationProvider"
class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
<property name="authenticationUserDetailsService">
<bean class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<constructor-arg ref="userService" />
</bean>
</property>
<property name="serviceProperties" ref="serviceProperties" />
<property name="ticketValidator">
<bean class="org.apereo.cas.client.validation.Cas20ServiceTicketValidator">
<constructor-arg index="0" value="https://:9443/cas" />
</bean>
</property>
<property name="key" value="an_id_for_this_auth_provider_only"/>
</bean>
<security:user-service id="userService">
<!-- Password is prefixed with {noop} to indicate to DelegatingPasswordEncoder that
NoOpPasswordEncoder should be used.
This is not safe for production, but makes reading
in samples easier.
Normally passwords should be hashed using BCrypt -->
<security:user name="joe" password="{noop}joe" authorities="ROLE_USER" />
...
</security:user-service>
CasAuthenticationProvider 使用 UserDetailsService 实例来加载用户通过 CAS 认证后的权限。我们在此处展示了一个简单的内存设置。请注意,CasAuthenticationProvider 实际上不使用密码进行认证,但它确实使用权限。
如果您回顾 CAS 工作原理部分,这些 bean 都相当自解释。
这完成了 CAS 的最基本配置。如果您没有犯任何错误,您的 Web 应用程序应该可以在 CAS 单点登录框架内愉快地工作。Spring Security 的其他部分无需担心 CAS 处理身份验证的事实。在以下部分中,我们将讨论一些(可选的)更高级的配置。
单点登出
CAS 协议支持单点登出,并且可以轻松添加到您的 Spring Security 配置中。以下是处理单点登出的 Spring Security 配置更新
<security:http entry-point-ref="casEntryPoint">
...
<security:logout logout-success-url="/cas-logout.jsp"/>
<security:custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER"/>
<security:custom-filter ref="singleLogoutFilter" before="CAS_FILTER"/>
</security:http>
<!-- This filter handles a Single Logout Request from the CAS Server -->
<bean id="singleLogoutFilter" class="org.apereo.cas.client.session.SingleSignOutFilter"/>
<!-- This filter redirects to the CAS Server to signal Single Logout should be performed -->
<bean id="requestSingleLogoutFilter"
class="org.springframework.security.web.authentication.logout.LogoutFilter">
<constructor-arg value="https://:9443/cas/logout"/>
<constructor-arg>
<bean class=
"org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
</constructor-arg>
<property name="filterProcessesUrl" value="/logout/cas"/>
</bean>
logout 元素将用户从本地应用程序登出,但不会结束与 CAS 服务器或已登录的其他应用程序的会话。requestSingleLogoutFilter 过滤器将允许请求 URL /spring_security_cas_logout 以将应用程序重定向到已配置的 CAS 服务器登出 URL。然后,CAS 服务器将向所有已登录的服务发送单点登出请求。singleLogoutFilter 通过在静态 Map 中查找 HttpSession 然后使其失效来处理单点登出请求。
为什么 logout 元素和 singleLogoutFilter 都需要,这可能令人困惑。首先进行本地登出被认为是最佳实践,因为 SingleSignOutFilter 只是将 HttpSession 存储在一个静态 Map 中,以便调用其 invalidate 方法。根据上述配置,登出流程将是:
-
用户请求
/logout,这将使用户从本地应用程序注销并将其发送到注销成功页面。 -
登出成功页面
/cas-logout.jsp应指示用户单击指向/logout/cas的链接以登出所有应用程序。 -
当用户点击链接时,用户将被重定向到 CAS 单点登出 URL (localhost:9443/cas/logout)。
-
在 CAS 服务器端,CAS 单点登出 URL 然后向所有 CAS 服务提交单点登出请求。在 CAS 服务端,Apereo 的
SingleSignOutFilter通过使原始会话失效来处理登出请求。
下一步是将以下内容添加到您的 web.xml
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>
org.apereo.cas.client.session.SingleSignOutHttpSessionListener
</listener-class>
</listener>
使用 SingleSignOutFilter 时,您可能会遇到一些编码问题。因此,建议添加 CharacterEncodingFilter 以确保在使用 SingleSignOutFilter 时字符编码正确。再次,请参阅 Apereo CAS 的文档以获取详细信息。SingleSignOutHttpSessionListener 确保当 HttpSession 过期时,用于单点登出的映射被移除。
使用 CAS 对无状态服务进行身份验证
本节描述如何使用 CAS 对服务进行身份验证。换句话说,本节讨论如何设置使用 CAS 进行身份验证的客户端。下一节描述如何设置使用 CAS 进行身份验证的无状态服务。
配置 CAS 以获取代理授权票据
为了向无状态服务进行身份验证,应用程序需要获取代理授予票据 (PGT)。本节描述如何配置 Spring Security 来获取 PGT,它建立在 cas-st[服务票据认证]配置之上。
第一步是在您的 Spring Security 配置中包含一个 ProxyGrantingTicketStorage。这用于存储由 CasAuthenticationFilter 获取的 PGT,以便它们可以用于获取代理票据。示例如下所示
<!--
NOTE: In a real application you should not use an in memory implementation.
You will also want to ensure to clean up expired tickets by calling
ProxyGrantingTicketStorage.cleanup()
-->
<bean id="pgtStorage" class="org.apereo.cas.client.proxy.ProxyGrantingTicketStorageImpl"/>
下一步是更新 CasAuthenticationProvider 以便能够获取代理票据。为此,将 Cas20ServiceTicketValidator 替换为 Cas20ProxyTicketValidator。proxyCallbackUrl 应设置为应用程序将接收 PGT 的 URL。最后,配置还应引用 ProxyGrantingTicketStorage,以便它可以使用 PGT 获取代理票据。您可以在下面找到应进行的配置更改示例。
<bean id="casAuthenticationProvider"
class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
...
<property name="ticketValidator">
<bean class="org.apereo.cas.client.validation.Cas20ProxyTicketValidator">
<constructor-arg value="https://:9443/cas"/>
<property name="proxyCallbackUrl"
value="https://:8443/cas-sample/login/cas/proxyreceptor"/>
<property name="proxyGrantingTicketStorage" ref="pgtStorage"/>
</bean>
</property>
</bean>
最后一步是更新 CasAuthenticationFilter 以接受 PGT 并将其存储在 ProxyGrantingTicketStorage 中。重要的是 proxyReceptorUrl 必须与 Cas20ProxyTicketValidator 的 proxyCallbackUrl 匹配。下面显示了一个示例配置。
<bean id="casFilter"
class="org.springframework.security.cas.web.CasAuthenticationFilter">
...
<property name="proxyGrantingTicketStorage" ref="pgtStorage"/>
<property name="proxyReceptorUrl" value="/login/cas/proxyreceptor"/>
</bean>
使用代理票据调用无状态服务
既然 Spring Security 获取 PGT,您可以使用它们创建代理票据,这些票据可用于对无状态服务进行身份验证。CAS 示例应用程序在 ProxyTicketSampleServlet 中包含一个工作示例。示例代码如下所示
-
Java
-
Kotlin
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// NOTE: The CasAuthenticationToken can also be obtained using
// SecurityContextHolder.getContext().getAuthentication()
final CasAuthenticationToken token = (CasAuthenticationToken) request.getUserPrincipal();
// proxyTicket could be reused to make calls to the CAS service even if the
// target url differs
final String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(targetUrl);
// Make a remote call using the proxy ticket
final String serviceUrl = targetUrl+"?ticket="+URLEncoder.encode(proxyTicket, "UTF-8");
String proxyResponse = CommonUtils.getResponseFromServer(serviceUrl, "UTF-8");
...
}
protected fun doGet(request: HttpServletRequest, response: HttpServletResponse?) {
// NOTE: The CasAuthenticationToken can also be obtained using
// SecurityContextHolder.getContext().getAuthentication()
val token = request.userPrincipal as CasAuthenticationToken
// proxyTicket could be reused to make calls to the CAS service even if the
// target url differs
val proxyTicket = token.assertion.principal.getProxyTicketFor(targetUrl)
// Make a remote call using the proxy ticket
val serviceUrl: String = targetUrl + "?ticket=" + URLEncoder.encode(proxyTicket, "UTF-8")
val proxyResponse = CommonUtils.getResponseFromServer(serviceUrl, "UTF-8")
}
代理票据认证
CasAuthenticationProvider 区分有状态和无状态客户端。有状态客户端是指任何向 CasAuthenticationFilter 的 filterProcessesUrl 提交请求的客户端。无状态客户端是指任何向 CasAuthenticationFilter 提交身份验证请求的客户端,其 URL 不是 filterProcessesUrl。
因为远程协议无法在 HttpSession 的上下文中呈现自身,所以无法依赖在请求之间将会话中的安全上下文存储在会话中的默认做法。此外,由于 CAS 服务器在 TicketValidator 验证票据后使其失效,因此在后续请求中呈现相同的代理票据将不起作用。
一个明显的选择是根本不为远程协议客户端使用 CAS。然而,这将消除 CAS 的许多理想功能。作为一种折衷方案,CasAuthenticationProvider 使用 StatelessTicketCache。这仅用于无状态客户端,这些客户端使用等于 CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER 的主体。发生的情况是 CasAuthenticationProvider 会将生成的 CasAuthenticationToken 存储在 StatelessTicketCache 中,以代理票据为键。因此,远程协议客户端可以呈现相同的代理票据,CasAuthenticationProvider 将无需联系 CAS 服务器进行验证(除了第一个请求)。一旦通过身份验证,代理票据可用于除原始目标服务之外的 URL。
本节建立在前面各节的基础上,以适应代理票据认证。第一步是指定认证所有工件,如下所示。
<bean id="serviceProperties"
class="org.springframework.security.cas.ServiceProperties">
...
<property name="authenticateAllArtifacts" value="true"/>
</bean>
下一步是为 CasAuthenticationFilter 指定 serviceProperties 和 authenticationDetailsSource。serviceProperties 属性指示 CasAuthenticationFilter 尝试认证所有工件,而不仅仅是 filterProcessesUrl 上存在的工件。ServiceAuthenticationDetailsSource 创建一个 ServiceAuthenticationDetails,确保在验证票据时,基于 HttpServletRequest 的当前 URL 用作服务 URL。生成服务 URL 的方法可以通过注入自定义 AuthenticationDetailsSource 返回自定义 ServiceAuthenticationDetails 来进行自定义。
<bean id="casFilter"
class="org.springframework.security.cas.web.CasAuthenticationFilter">
...
<property name="serviceProperties" ref="serviceProperties"/>
<property name="authenticationDetailsSource">
<bean class=
"org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource">
<constructor-arg ref="serviceProperties"/>
</bean>
</property>
</bean>
您还需要更新 CasAuthenticationProvider 以处理代理票据。为此,请将 Cas20ServiceTicketValidator 替换为 Cas20ProxyTicketValidator。您需要配置 statelessTicketCache 以及您希望接受的代理。您可以在下面找到接受所有代理所需的更新示例。
<bean id="casAuthenticationProvider"
class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
...
<property name="ticketValidator">
<bean class="org.apereo.cas.client.validation.Cas20ProxyTicketValidator">
<constructor-arg value="https://:9443/cas"/>
<property name="acceptAnyProxy" value="true"/>
</bean>
</property>
<property name="statelessTicketCache">
<bean class="org.springframework.security.cas.authentication.SpringCacheBasedTicketCache">
<property name="cache">
<bean class="net.sf.ehcache.Cache"
init-method="initialise" destroy-method="dispose">
<constructor-arg value="casTickets"/>
<constructor-arg value="50"/>
<constructor-arg value="true"/>
<constructor-arg value="false"/>
<constructor-arg value="3600"/>
<constructor-arg value="900"/>
</bean>
</property>
</bean>
</property>
</bean>