diff --git a/web/src/main/java/org/springframework/security/web/access/HttpStatusAccessDeniedHandler.java b/web/src/main/java/org/springframework/security/web/access/HttpStatusAccessDeniedHandler.java new file mode 100644 index 00000000000..70c7c8ef5c6 --- /dev/null +++ b/web/src/main/java/org/springframework/security/web/access/HttpStatusAccessDeniedHandler.java @@ -0,0 +1,24 @@ +package org.springframework.security.web.access; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.util.Assert; + +import java.io.IOException; + +public class HttpStatusAccessDeniedHandler implements AccessDeniedHandler { + private final HttpStatus httpStatus; + + public HttpStatusAccessDeniedHandler(HttpStatus httpStatus) { + Assert.notNull(httpStatus, "httpStatus cannot be null"); + this.httpStatus = httpStatus; + } + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { + response.sendError(this.httpStatus.value(), accessDeniedException.getMessage()); + } +}