RestAuthenticationEntryPoint.java
package cl.prgm.portaltrip.infrastructure.security;
import java.io.IOException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import tools.jackson.databind.json.JsonMapper;
import cl.prgm.portaltrip.infrastructure.web.dto.ApiResponseDto;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
private final JsonMapper jsonMapper;
public RestAuthenticationEntryPoint(JsonMapper jsonMapper) {
this.jsonMapper = jsonMapper;
}
@Override
public void commence(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
jsonMapper.writeValue(
response.getOutputStream(),
ApiResponseDto.error(HttpStatus.UNAUTHORIZED, "Authentication required"));
}
}