CAS 5.2.0 OAuth2:如何在用户Profile接口返回Client-ID
在CAS 5.2.0的OAuth2.0 Profile接口中添加Client-ID完全可行
当然可以实现这个需求!CAS 5.2.0的OAuth2 profile端点默认不会返回client_id,但我们可以通过自定义响应生成逻辑来添加这个字段。下面是具体的实现步骤:
核心思路
CAS的/cas/oauth2.0/profile接口的响应是由OAuth20UserProfileView类负责生成的。我们只需要继承这个类,重写它的响应渲染方法,把当前请求对应的client_id注入到返回的JSON结构中即可。
1. 编写自定义的Profile视图类
创建一个Java类,继承原有的OAuth20UserProfileView,修改响应数据的生成逻辑:
import org.apereo.cas.support.oauth.OAuth20Constants; import org.apereo.cas.support.oauth.web.views.OAuth20UserProfileView; import org.apereo.cas.support.oauth.services.OAuth20Client; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; public class CustomOAuth20UserProfileView extends OAuth20UserProfileView { @Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { // 从model中获取当前授权的客户端对象 OAuth20Client client = (OAuth20Client) model.get(OAuth20Constants.CLIENT); // 获取原始的profile响应数据 Map<String, Object> profile = (Map<String, Object>) model.get("profile"); // 添加client_id字段到profile中 if (client != null) { profile.put("client_id", client.getId()); } // 使用CAS自带的ObjectMapper序列化并输出响应 this.objectMapper.writeValue(response.getWriter(), profile); } }
2. 替换默认的Spring Bean
创建一个自定义配置类,把我们的自定义视图注册为Spring Bean,替换掉CAS默认的OAuth20UserProfileView:
import org.apereo.cas.support.oauth.web.views.OAuth20UserProfileView; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CustomOAuth2Configuration { @Bean public OAuth20UserProfileView oauth20UserProfileView() { return new CustomOAuth20UserProfileView(); } }
3. 集成到CAS服务器
如果你使用的是CAS Overlay模板项目(推荐方式),直接把上面两个类放到src/main/java对应的包路径下(比如com.yourcompany.cas.custom),然后重新构建并部署CAS即可。
如果是传统的WAR部署方式,需要把编译好的类打包成JAR,放到CAS WAR包的WEB-INF/lib目录下,同时确保自定义配置类被Spring扫描到。
4. 验证结果
重启CAS后,用合法的OAuth2客户端发起授权并调用/cas/oauth2.0/profile接口,你会看到响应已经包含了client_id字段:
{ "attributes": { ... }, "id": "
", "client_id": " " }
注意事项
- 确保请求是经过合法授权的,否则CAS无法获取到对应的客户端信息,
client_id字段可能不会出现或者为null。 - 如果你的CAS已经有其他自定义OAuth2配置,要注意避免Bean冲突。
- 建议使用CAS Overlay模板来管理自定义扩展,这样后续CAS版本升级会更方便。
内容的提问来源于stack exchange,提问作者Stefan
相关产品推荐
相关产品推荐

