How let spring security response unauthorized(http 401 code) if requesting uri without authentication
In spring boot 2, there is no more Http401AuthenticationEntryPoint
, instead you can use HttpStatusEntryPoint which return a response with the corresponding status
http
.exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
Update your Spring Boot version to 1.3.0.RELEASE and you'll get Http401AuthenticationEntryPoint
for free. Configure authentication entry point in your security configuration like this:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(PROTECTED_RESOURCES)
.hasRole("USER")
.anyRequest()
.permitAll()
.and()
.anonymous().disable()
.exceptionHandling()
.authenticationEntryPoint(new org.springframework.boot.autoconfigure.security.Http401AuthenticationEntryPoint("headerValue"));
}
and Spring Boot will return HTTP 401
:
Status Code: 401 Unauthorized
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Expires: 0
Pragma: no-cache
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
WWW-Authenticate: headerValue
X-Content-Type-Options: nosniff
x-xss-protection: 1; mode=block
You need to extend AuthenticationEntryPoint to do customization based upon the exceptions or reason of Auth Failure.
@ControllerAdvice
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
// 401
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed");
}
@ExceptionHandler (value = {AccessDeniedException.class})
public void commence(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException {
// 403
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization Failed : " + accessDeniedException.getMessage());
}
@ExceptionHandler (value = {Exception.class})
public void commence(HttpServletRequest request, HttpServletResponse response,
Exception exception) throws IOException {
// 500
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error : " + exception.getMessage());
}
}
Specify the above custom AuthenticationEntryPoint in your SecurityConfig like below:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity (prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
.authenticationEntryPoint(new MyAuthenticationEntryPoint());
}
}