BaseAuthenticationEntryPoint.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package com.keao.edu.common.security;
  2. import com.keao.edu.common.constant.CommonConstants;
  3. import com.keao.edu.common.entity.HttpResponseResult;
  4. import org.apache.commons.lang3.exception.ExceptionUtils;
  5. import org.codehaus.jackson.map.ObjectMapper;
  6. import org.springframework.http.MediaType;
  7. import org.springframework.security.authentication.InsufficientAuthenticationException;
  8. import org.springframework.security.core.AuthenticationException;
  9. import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
  10. import org.springframework.security.web.AuthenticationEntryPoint;
  11. import org.springframework.stereotype.Component;
  12. import javax.servlet.ServletException;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import java.io.IOException;
  16. import java.io.PrintWriter;
  17. @Component
  18. public class BaseAuthenticationEntryPoint implements AuthenticationEntryPoint {
  19. @Override
  20. public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
  21. response.setCharacterEncoding(CommonConstants.UTF8);
  22. response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
  23. response.setStatus(HttpServletResponse.SC_OK);
  24. PrintWriter printWriter = response.getWriter();
  25. Throwable e = ExceptionUtils.getRootCause(authException);
  26. if (e == null) {
  27. e = authException;
  28. }
  29. int errorCode = 500;
  30. if (e instanceof InvalidTokenException) {
  31. errorCode = HttpServletResponse.SC_UNAUTHORIZED;
  32. }
  33. if (e instanceof InsufficientAuthenticationException) {
  34. errorCode = HttpServletResponse.SC_FORBIDDEN;
  35. }
  36. HttpResponseResult result = new HttpResponseResult(false, errorCode, null, e.getMessage());
  37. ObjectMapper objectMapper = new ObjectMapper();
  38. printWriter.append(objectMapper.writeValueAsString(result));
  39. }
  40. }