Azure AD认证后出现字符解码问题的技术求助
解决方案建议
核心原因分析
添加Azure AD OAuth2 SSO依赖后,Spring Security的自动配置会默认拦截所有HTTP请求,包括你调用Hashicorp Vault的内部REST请求,导致该请求被错误引导至Azure AD的认证页面(返回HTML内容,因此JSON解析时遇到<字符),而非正常发送到Vault服务。
具体解决步骤
配置Spring Security忽略Vault请求路径
在Spring Security配置类中添加对Vault请求路径的忽略规则,确保内部调用不会被OAuth2认证拦截:@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override public void configure(WebSecurity web) throws Exception { // 替换为你的Vault请求实际路径,例如"/vault/api/**" web.ignoring().antMatchers("/vault/**"); } // 其他OAuth2相关配置... }若使用Spring Security 5.7+的无
WebSecurityConfigurerAdapter配置方式:@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http // 其他OAuth2配置... .authorizeHttpRequests(auth -> auth .requestMatchers("/vault/**").permitAll() // 允许Vault请求无需认证 .anyRequest().authenticated() ); return http.build(); } @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring().requestMatchers("/vault/**"); } }隔离Vault调用的HTTP客户端实例
确认调用Vault的RestTemplate或WebClient没有被自动注入OAuth2令牌拦截器,单独创建一个用于Vault调用的实例:@Bean("vaultRestTemplate") public RestTemplate vaultRestTemplate() { return new RestTemplate(); }调用Vault时注入该特定实例:
@Autowired @Qualifier("vaultRestTemplate") private RestTemplate vaultRestTemplate;验证Vault请求的原始返回内容
临时在调用代码中打印返回的原始内容,确认是否为Azure AD的认证跳转页面(含<html>标签),以此验证拦截规则是否生效:ResponseEntity<String> response = vaultRestTemplate.getForEntity(vaultUrl, String.class); System.out.println("Vault原始返回内容: " + response.getBody());确认配置优先级
若存在多个Security配置类,通过@Order注解指定自定义配置的优先级,确保其先于OAuth2自动配置生效。
内容的提问来源于stack exchange,提问作者Jon H
相关产品推荐
相关产品推荐

