Spring Boot集成Keycloak:为指定端点添加API Key认证
实现方案
要实现仅/b/order端点使用请求头静态API Key认证,其余端点保留原有Keycloak+IP白名单逻辑,可按以下步骤修改:
1. 配置静态API Key
首先在配置文件(如application.yml)中添加API Key参数:
app: api-key: b-order: "YOUR_STATIC_API_KEY_HERE"
2. 自定义API Key认证过滤器
创建一个过滤器,专门验证/b/order请求头中的API Key:
@Component @Slf4j public class ApiKeyAuthFilter extends OncePerRequestFilter { @Value("${app.api-key.b-order}") private String validApiKey; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 仅对/b/order路径生效 if ("/b/order".equals(request.getRequestURI())) { String requestApiKey = request.getHeader("X-API-Key"); if (validApiKey == null || !validApiKey.equals(requestApiKey)) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getWriter().write("Invalid or missing API Key"); return; } } filterChain.doFilter(request, response); } }
3. 修改Security配置类
调整原有KeycloakSecurityConfig,移除/b/order的IP白名单规则,添加API Key过滤器,并确保Keycloak认证不对该路径生效:
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(jsr250Enabled = true) @Slf4j public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter { @Autowired List<String> aIPWhiteList; @Autowired private ApiKeyAuthFilter apiKeyAuthFilter; @Override protected void configure(HttpSecurity http) throws Exception { // 先添加API Key过滤器,优先级高于Keycloak认证 http.addFilterBefore(apiKeyAuthFilter, KeycloakAuthenticationProcessingFilter.class); super.configure(http); String aIPAddressesFilterStr = defineIPFilters(aIPWhiteList); http.authorizeRequests() .antMatchers("/order/a/**").access(aIPAddressesFilterStr) // /b/order的认证已由过滤器处理,直接放行 .antMatchers("/b/order").permitAll() .anyRequest().permitAll(); http.cors().and().csrf().disable(); // 让Keycloak认证逻辑忽略/b/order路径 http.requestMatcher(new NegatedRequestMatcher(new AntPathRequestMatcher("/b/order"))); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) { KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider(); keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper()); auth.authenticationProvider(keycloakAuthenticationProvider); } @Bean @Override protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()); } private String defineIPFilters(List<String> whiteList) { if (whiteList.isEmpty()) { return ""; } StringBuilder ipAddressesFilterStr = new StringBuilder(); for (String ip : whiteList) { ipAddressesFilterStr.append("hasIpAddress('").append(ip).append("') or "); } return ipAddressesFilterStr.substring(0, ipAddressesFilterStr.length() - 4); } }
关键说明
- 自定义过滤器
ApiKeyAuthFilter会优先执行,专门拦截/b/order请求完成API Key验证 - 通过
NegatedRequestMatcher让Keycloak认证逻辑跳过/b/order路径,避免重复认证 - 原有的
/order/a/**端点仍保留IP白名单+Keycloak认证逻辑
内容的提问来源于stack exchange,提问作者FrancMo
相关产品推荐
相关产品推荐

