You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

授权头缺失bearer token时不将API请求重定向至登录页的配置问题

问题根因

默认的KeycloakAuthenticationEntryPoint只会在请求匹配指定规则 且 请求头的Authorization字段是Bearer开头时,才会返回401状态码。如果Authorization头存在但不是Bearer格式,就会跳过401逻辑,直接走登录页重定向。

解决方案

方案1:自定义认证入口点(改动最小,推荐)

扩展原有Keycloak认证入口点,新增Authorization头存在判断逻辑,只要请求携带Authorization头,不管格式是否为Bearer,都优先返回401。

  1. 实现自定义EntryPoint
import org.springframework.http.HttpHeaders
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.keycloak.adapters.AdapterDeploymentContext
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationEntryPoint
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.util.matcher.RequestMatcher

class CustomKeycloakAuthEntryPoint(
    adapterDeploymentContext: AdapterDeploymentContext,
    private val webPathMatcher: RequestMatcher
) : KeycloakAuthenticationEntryPoint(adapterDeploymentContext) {

    override fun commence(
        request: HttpServletRequest,
        response: HttpServletResponse,
        authException: AuthenticationException
    ) {
        // 满足以下任意条件返回401:1. 非Web界面路径 2. 携带Authorization头
        val return401 = !webPathMatcher.matches(request) 
                || request.getHeader(HttpHeaders.AUTHORIZATION) != null
        if (return401) {
            response.status = HttpServletResponse.SC_UNAUTHORIZED
            response.contentType = "application/json;charset=UTF-8"
            response.writer.write("{\"code\":401,\"message\":\"未认证\"}")
            return
        }
        // Web界面请求走原有重定向逻辑
        super.commence(request, response, authException)
    }
}
  1. 替换原有EntryPoint配置
    修改你现有SecurityConfiguration类中的authenticationEntryPoint方法:
override fun authenticationEntryPoint(): AuthenticationEntryPoint? {
    val webPathMatcher = OrRequestMatcher(
        WEBAPP_ANT_PATHS.map { AntPathRequestMatcher(it) }
    )
    return CustomKeycloakAuthEntryPoint(adapterDeploymentContext(), webPathMatcher)
}

方案2:拆分多套安全配置(适合路径划分清晰的场景)

如果你的API和Web界面路径完全独立,可以定义两个SecurityFilterChain分别处理两类请求:

  • API路径的过滤器链设置bearer-only=true,所有未认证请求直接返回401
  • Web界面路径的过滤器链走默认的重定向登录逻辑

注意事项

如果后续新增其他Web界面路径,记得同步添加到WEBAPP_ANT_PATHS列表中,避免访问前端页面时无法正常跳转到登录页。

内容的提问来源于stack exchange,提问作者Jan Gassen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 00:39:02