0 day streak
java / expert
Snippet

Refining API Error Responses with AuthenticationEntryPoint

AuthenticationEntryPoint is triggered when an unauthenticated user attempts to access a protected resource. Implementing this allows for returning structured JSON errors instead of default HTML redirect pages in REST APIs.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
@Component
public class ApiAuthEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json");
response.getWriter().write("{\"error\": \"Invalid credentials\", \"timestamp\": \"" + Instant.now() + "\"}");
}
}
spring
Breakdown
1
commence(...)
Method executed when authentication fails, providing access to the response stream.
2
SC_UNAUTHORIZED
Standard HTTP 401 status code indicating that authentication is required.