|
| 1 | +package uk.gov.laa.ccms.springboot.auth; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 4 | +import jakarta.servlet.ServletException; |
| 5 | +import jakarta.servlet.http.HttpServletRequest; |
| 6 | +import jakarta.servlet.http.HttpServletResponse; |
| 7 | +import jakarta.ws.rs.core.Response; |
| 8 | +import lombok.extern.slf4j.Slf4j; |
| 9 | +import org.springframework.beans.factory.annotation.Autowired; |
| 10 | +import org.springframework.http.MediaType; |
| 11 | +import org.springframework.security.access.AccessDeniedException; |
| 12 | +import org.springframework.security.web.access.AccessDeniedHandler; |
| 13 | +import org.springframework.stereotype.Component; |
| 14 | + |
| 15 | +import java.io.IOException; |
| 16 | + |
| 17 | +@Slf4j |
| 18 | +@Component |
| 19 | +public class ApiAccessDeniedHandler implements AccessDeniedHandler { |
| 20 | + |
| 21 | + ObjectMapper objectMapper; |
| 22 | + |
| 23 | + @Autowired |
| 24 | + ApiAccessDeniedHandler(ObjectMapper objectMapper) { |
| 25 | + this.objectMapper = objectMapper; |
| 26 | + } |
| 27 | + |
| 28 | + @Override |
| 29 | + public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { |
| 30 | + int code = HttpServletResponse.SC_FORBIDDEN; |
| 31 | + response.setStatus(code); |
| 32 | + response.setContentType(MediaType.APPLICATION_JSON_VALUE); |
| 33 | + |
| 34 | + String status = Response.Status.FORBIDDEN.getReasonPhrase(); |
| 35 | + String message = accessDeniedException.getMessage(); |
| 36 | + |
| 37 | + ErrorResponse errorResponse = new ErrorResponse(code, status, message); |
| 38 | + |
| 39 | + response.getWriter().write(objectMapper.writeValueAsString(errorResponse)); |
| 40 | + |
| 41 | + log.info("Request rejected for endpoint '{}': {}", request.getRequestURI(), message); |
| 42 | + } |
| 43 | + |
| 44 | +} |
0 commit comments