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

Spring Boot 6中AuthenticationEntryPoint移除后,如何实现其原有机制?

Spring Boot 6.1中替代AuthenticationEntryPoint原有逻辑的实现方案

在Spring Boot 6.1对应的Spring Security版本中,AuthenticationEntryPoint接口并未被移除,只是旧的配置方式有所调整。针对你提供的无状态JWT认证场景,只需通过exceptionHandling配置项即可集成自定义的认证入口逻辑,实现未认证请求的统一处理。

具体实现

  1. 编写自定义AuthenticationEntryPoint
    实现AuthenticationEntryPoint接口,定义未认证时的响应逻辑(比如返回JSON格式的错误信息):

    import jakarta.servlet.http.HttpServletRequest;
    import jakarta.servlet.http.HttpServletResponse;
    import org.springframework.security.core.AuthenticationException;
    import org.springframework.security.web.AuthenticationEntryPoint;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.io.IOException;
    import java.util.Map;
    
    public class CustomAuthEntryPoint implements AuthenticationEntryPoint {
    
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    
            Map<String, Object> errorResponse = Map.of(
                "code", HttpServletResponse.SC_UNAUTHORIZED,
                "message", "请求未授权,请先完成认证"
            );
    
            new ObjectMapper().writeValue(response.getOutputStream(), errorResponse);
        }
    }
    
  2. 更新SecurityFilterChain配置
    在现有配置中添加exceptionHandling块,注入自定义的AuthenticationEntryPoint:

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .addFilterBefore(new JwtAuthenticationFilter(userDetailsService, jwtTokenHelper), UsernamePasswordAuthenticationFilter.class)
                .csrf(csrf -> csrf.disable())
                .authorizeHttpRequests(request -> {
                    request
                            .requestMatchers("/api/v1/auth/**").permitAll()
                            .anyRequest().authenticated();
                })
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 配置认证异常处理,挂载自定义入口点
                .exceptionHandling(exceptionConfig -> 
                    exceptionConfig.authenticationEntryPoint(new CustomAuthEntryPoint())
                )
                .logout(LogoutConfigurer::permitAll);
        return httpSecurity.build();
    }
    

补充说明

  • AuthenticationEntryPoint的核心作用依然是拦截未认证请求、触发自定义响应逻辑,这一点和旧版本一致,只是配置时需要通过exceptionHandling()方法来挂载。
  • 如果需要处理权限不足的场景,可以在exceptionHandling中同时配置accessDeniedHandler(),实现类似的自定义响应逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 07:31:21