AnonymousAuthenticationEntryPoint.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package com.genersoft.iot.vmp.conf.security;
  2. import com.alibaba.fastjson2.JSONObject;
  3. import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
  4. import org.apache.poi.hssf.eventmodel.ERFListener;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.security.core.AuthenticationException;
  8. import org.springframework.security.web.AuthenticationEntryPoint;
  9. import org.springframework.stereotype.Component;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import java.io.IOException;
  13. /**
  14. * 处理匿名用户访问逻辑
  15. * @author lin
  16. */
  17. @Component
  18. public class AnonymousAuthenticationEntryPoint implements AuthenticationEntryPoint {
  19. private final static Logger logger = LoggerFactory.getLogger(DefaultUserDetailsServiceImpl.class);
  20. @Override
  21. public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
  22. // 允许跨域
  23. response.setHeader("Access-Control-Allow-Origin", "*");
  24. // 允许自定义请求头token(允许head跨域)
  25. response.setHeader("Access-Control-Allow-Headers", "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");
  26. response.setHeader("Content-type", "application/json;charset=UTF-8");
  27. JSONObject jsonObject = new JSONObject();
  28. jsonObject.put("code", ErrorCode.ERROR401.getCode());
  29. jsonObject.put("msg", ErrorCode.ERROR401.getMsg());
  30. String logUri = "api/user/login";
  31. if (request.getRequestURI().contains(logUri)){
  32. jsonObject.put("msg", e.getMessage());
  33. }
  34. response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  35. try {
  36. response.getWriter().print(jsonObject.toJSONString());
  37. } catch (IOException ioException) {
  38. ioException.printStackTrace();
  39. }
  40. }
  41. }