Skip to content

Commit f2162e6

Browse files
committed
add access denied handler
1 parent 56aae2e commit f2162e6

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
}

laa-ccms-spring-boot-starters/laa-ccms-spring-boot-starter-auth/src/main/java/uk/gov/laa/ccms/springboot/auth/SecurityFilterChainAutoConfiguration.java

+4-1
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,10 @@ public SecurityFilterChain filterProtectedURIs(HttpSecurity httpSecurity) throws
132132
.sessionManagement(sessionManagement ->
133133
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
134134
)
135-
.addFilterBefore(apiAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
135+
.addFilterBefore(apiAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
136+
.exceptionHandling(exceptionHandling -> {
137+
exceptionHandling.accessDeniedHandler(new ApiAccessDeniedHandler(objectMapper));
138+
});
136139

137140
return httpSecurity.build();
138141

0 commit comments

Comments
 (0)