Spring Security整合CAS部署Tomcat后/login/cas未被监听报错咨询
问题1:/login/cas路径未触发认证流程的根因及修复
你当前代码存在核心缺失:仅将CasAuthenticationFilter注册为Spring Bean,没有将该过滤器添加到Spring Security的过滤器链中,自然无法拦截处理对应路径的请求。
修复方案:
- 在
WebSecurityConfig类中注入你定义的CasAuthenticationFilterBean - 在
configure(HttpSecurity http)方法的过滤器配置部分,添加该过滤器,示例修改如下:
@Autowired private CasAuthenticationFilter casAuthenticationFilter; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers( "/secured", "/login").authenticated() .and() .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()) .and() .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class) .addFilterBefore(logoutFilter, LogoutFilter.class) // 新增:添加CAS认证过滤器到链中 .addFilter(casAuthenticationFilter) .csrf().ignoringAntMatchers("/exit/cas"); }
由于你配置了server.servlet.contextPath=/cas-secured-app-0.0.1-SNAPSHOT,Spring Security过滤器的路径匹配默认是基于contextPath的,CasAuthenticationFilter默认监听的/login/cas可以正确匹配/{contextPath}/login/cas的请求,无需额外修改路径配置,如有匹配异常可手动指定:
@Bean public CasAuthenticationFilter casAuthenticationFilter( AuthenticationManager authenticationManager, ServiceProperties serviceProperties) throws Exception { CasAuthenticationFilter filter = new CasAuthenticationFilter(); filter.setAuthenticationManager(authenticationManager); filter.setServiceProperties(serviceProperties); // 手动指定监听路径 filter.setFilterProcessesUrl("/login/cas"); return filter; }
问题2:CAS服务端记录的service地址与配置不一致的根因及修复
该问题是默认CAS服务端的访问限制导致的:
默认部署的Apereo CAS服务端内置的服务注册列表,仅允许来自localhost、127.0.0.1域名的应用接入。你配置的service域名是tomcat-docker,不在默认允许的白名单内,CAS会自动将service替换为请求来源的localhost地址,因此日志中记录的是localhost路径。
修复方案:
修改CAS服务端的服务注册配置,添加允许https://tomcat-docker:8443/**格式的应用接入即可,无需修改应用侧代码。如果是本地测试场景,也可以直接通过https://localhost:8443开头的地址访问应用,同时将ServiceProperties里的service地址改为对应的localhost路径即可匹配。
内容的提问来源于stack exchange,提问作者Juan Solo

