Spring Boot集成Keycloak时permitAll接口带过期token返回401如何解决
问题根因
- 你当前使用
HttpSecurity配置的permitAll规则仅为授权层面的放行,不会跳过Keycloak的前置认证过滤器 - 只要请求头携带
access_token,无论路径是否配置permitAll,Keycloak认证过滤器都会优先校验token有效性,过期就直接返回401,不会进入业务接口 - Postman不带
access_token时请求正常,就是因为没有触发Keycloak的token校验逻辑,和你遇到的现象完全吻合
解决方案
- 放开你注释掉的
WebSecurity配置,该配置会直接将目标路径排除在整个Spring Security过滤器链之外,Keycloak的校验逻辑完全不会处理该路径的请求:
@Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers(HttpMethod.GET,"/v1/users/current"); }
- 可选优化:调整
HttpSecurity的配置顺序,将所有放行路径统一放在最前面,避免匹配顺序导致的规则失效,修改后的configure(HttpSecurity http)参考如下:
@Override public void configure(HttpSecurity http) throws Exception { http .csrf().disable() .cors().configurationSource(corsConfigurationSource()) .and() .authorizeRequests() // 所有放行路径统一前置 .antMatchers(HttpMethod.GET,"/v1/users/current").permitAll() .antMatchers(HttpMethod.POST,"/login").permitAll() // 权限校验规则 .antMatchers(HttpMethod.POST,"/register/admin").hasRole("admin") .antMatchers(HttpMethod.POST, "/*").authenticated() .anyRequest().permitAll(); }
配置生效后,/v1/users/current路径的所有请求都会直接进入你的业务接口,你可以自行在接口内完成token有效性校验、用refresh_token换发新access_token的逻辑,不会再被Keycloak提前拦截返回401。如果有其他同类不需要Keycloak校验的接口,也可以直接添加到web.ignoring()的匹配规则中。
内容的提问来源于stack exchange,提问作者Denis Stojković Stole
相关产品推荐
相关产品推荐

