升级至Spring Boot 2.0.0.RELEASE后,Http401AuthenticationEntryPoint类是否存在?
Hey there! Let's clear this up for you:
- Short answer: The
org.springframework.boot.autoconfigure.security.Http401AuthenticationEntryPointclass no longer exists in Spring Boot 2.0.0.RELEASE and later versions. It was removed during the major security module refactor in Spring Boot 2.x.
What to use instead
Since your goal is to return an HTTP 401 (Unauthorized) instead of 403 (Forbidden) for unauthenticated requests, you have two clean options in Spring Boot 2.x:
1. Create a custom AuthenticationEntryPoint
You can build your own simple implementation of Spring Security's AuthenticationEntryPoint interface:
import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class Custom401EntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } }
Then register it in your security configuration:
import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .exceptionHandling() .authenticationEntryPoint(new Custom401EntryPoint()); } }
2. Use Spring Security's native HttpStatusEntryPoint
For a more concise approach, use the HttpStatusEntryPoint (available in Spring Security 5.0+, which is integrated with Spring Boot 2.x) to directly return the 401 status code:
import org.springframework.security.web.authentication.HttpStatusEntryPoint; import javax.servlet.http.HttpServletResponse; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .exceptionHandling() .authenticationEntryPoint(new HttpStatusEntryPoint(HttpServletResponse.SC_UNAUTHORIZED)); } }
Why was the old class removed?
Spring Boot 2.0 underwent significant refactoring of its security auto-configuration to align more closely with native Spring Security features. The old Http401AuthenticationEntryPoint was a Boot-specific helper that became redundant once Spring Security provided equivalent (and more flexible) native components like HttpStatusEntryPoint.
内容的提问来源于stack exchange,提问作者lealceldeiro

