CustomAuthenticationFailureHandler.java 970 B

123456789101112131415161718192021
  1. package com.hichina.admin.hichinaadminbackend.config;
  2. import jakarta.servlet.http.HttpServletRequest;
  3. import jakarta.servlet.http.HttpServletResponse;
  4. import org.springframework.http.HttpStatus;
  5. import org.springframework.security.core.AuthenticationException;
  6. import org.springframework.security.web.authentication.AuthenticationFailureHandler;
  7. import java.io.IOException;
  8. import java.util.Calendar;
  9. public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
  10. @Override
  11. public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
  12. httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
  13. String jsonPayload = "{\"message\" : \"%s\", \"timestamp\" : \"%s\" }";
  14. httpServletResponse.getOutputStream().println(String.format(jsonPayload, e.getMessage(), Calendar.getInstance().getTime()));
  15. }
  16. }