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
1
2
3
4
5
6
7
8
9
10
@Componentpublic class ApiAuthEntryPoint implements AuthenticationEntryPoint {@Overridepublic 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.