Apereo CAS 之 支持OAuth2
Apereo CAS 通过使用 bridge 模式来支持多个协议:CAS、SAML2、OAuth2、OpenID Connect 等。
CAS 可部署软件包中已经包含了可以使用 SAML2、OAuth2 等协议的 plugin/bridges/modules,这些 plugins 模块都是和 CAS 通信。 可参考:https://apereo.github.io/cas/6.5.x/protocol/Protocol-Overview.html。
The right-hand side of that equation is always CAS when you consider, as an example, the following authentication flow with an OAuth2-enabled client application:
- The CAS deployment has turned on the OAuth2 plugin.
- An OAuth2 authorization request is submitted to the relevant CAS endpoint.
- The OAuth2 plugin verifies the request and translates it to a CAS authentication request!
- The authentication request is routed to the relevant CAS login endpoint.
- User authenticates and CAS routes the flow back to the OAuth2 plugin, having issued a service ticket for the plugin.
- The OAuth2 plugin attempts to validate that ticket to retrieve the necessary user profile and attributes.
- The OAuth2 plugin then proceeds to issue the right OAuth2 response by translating and transforming the profile and validated assertions into what the client application may need.
1. 添加依赖库
implementation "org.apereo.cas:cas-server-support-oauth-webflow"
2. Enable Actuator Endpoints (Optional)
添加依赖,并设置开放 oauthd 的 actuator 端点。
implementation "org.apereo.cas:cas-server-support-reports"
management.endpoint.oauthTokens.enabled=true
management.endpoints.web.exposure.include=oauthTokens
cas.monitor.endpoints.endpoint.oauthTokens.access=PERMIT
通过访问 https://localhost:8443/cas/actuator/ 应该可以看到 OAuth 相关 endpoints。
3. 定义一个 OAuth Client
可以通过设置
cas.service-registry.json.location=classpath:/services
cas.service-registry.core.init-from-json=true
在 cas-overlay-template 的 resources/services 下定义文件 OAuth2DemoClient-2001.json 包含以下内容来把这个 OAuth2 Client ‘OAuth2DemoClient’ 自动导入到 MongoDB 的 cas_serviceregistry collection。
{
"@class" : "org.apereo.cas.support.oauth.services.OAuthRegisteredService",
"clientId": "oauth2DemoClientID",
"clientSecret": "clientSecret",
"serviceId" : "^(https|imaps)://<redirect-uri>.*",
"name" : "OAuth2DemoClient",
"id" : 2001,
"supportedGrantTypes": [ "java.util.HashSet", [ "password", "authorization_code", "client_credentials", "refresh_token"] ],
"supportedResponseTypes": [ "java.util.HashSet", [ "token", "code", "device_code"] ]
}
grant 是获得 AccessToken 的方式/方法,这篇文章对此进行了详细介绍:https://alexbilbie.com/guide-to-oauth-2-grants/。
4. 重启、查看
运行 ./gradlew clean copyCasConfiguration build run
后,查看 db.getCollection('cas_serviceregistry').find({})
应该可以看到 id 为 2001 的 OAutho client 定义。
通过 CAS Management UI 也可以看到刚刚添加的‘OAuth2DemoClient’:
至此,我们以及把 Apereo CAS 配置成支持 OAuth2 协议。
Reference:
[1]: https://apereo.github.io/cas/6.5.x/protocol/Protocol-Overview.html
[2]: https://alexbilbie.com/guide-to-oauth-2-grants/
[3]: https://dacurry-tns.github.io/deploying-apereo-cas/building_server_service-registry_configure-the-service-registry.html