RestfulBasicAuthenticationEntryPoint.java

  1. package cn.home1.oss.lib.security.internal.rest;

  2. import static org.apache.commons.lang3.StringUtils.isBlank;

  3. import cn.home1.oss.lib.errorhandle.internal.RestfulExceptionHandler;

  4. import lombok.Getter;
  5. import lombok.NonNull;

  6. import org.springframework.beans.factory.InitializingBean;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.security.core.AuthenticationException;
  9. import org.springframework.security.web.AuthenticationEntryPoint;

  10. import java.io.IOException;

  11. import javax.servlet.ServletException;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;

  14. /**
  15.  * Created by zhanghaolun on 16/6/28.
  16.  */
  17. public class RestfulBasicAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean {

  18.   public static final String DEFAULT_REALM_NAME = "DefaultRealmName";

  19.   @Getter
  20.   private String realmName;

  21.   @Autowired
  22.   @NonNull
  23.   private RestfulExceptionHandler exceptionHandler;

  24.   @Override
  25.   public void commence( //
  26.     final HttpServletRequest request, //
  27.     final HttpServletResponse response, //
  28.     final AuthenticationException authException //
  29.   ) throws IOException, ServletException {
  30.     response.addHeader("WWW-Authenticate", "Basic realm=\"" + this.realmName + "\"");

  31.     // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  32.     // response.getWriter().println("HTTP Status 401 - " + authException.getMessage());
  33.     this.exceptionHandler.resolveAndHandle(request, response, authException);
  34.   }

  35.   @Override
  36.   public void afterPropertiesSet() throws Exception {
  37.     if (isBlank(this.getRealmName())) {
  38.       this.setRealmName(DEFAULT_REALM_NAME);
  39.     }
  40.     // Assert.hasText(this.realmName, "realmName must be specified");
  41.   }

  42.   public void setRealmName(final String realmName) {
  43.     this.realmName = realmName;
  44.   }

  45.   public void setExceptionHandler(final RestfulExceptionHandler exceptionHandler) {
  46.     this.exceptionHandler = exceptionHandler;
  47.   }
  48. }