content: package com.xiyan.filter;
  
  import com.fasterxml.jackson.databind.ObjectMapper;
  import org.springframework.http.MediaType;
  import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  import org.springframework.security.core.Authentication;
  import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.IOException;
  import java.io.InputStream;
  import java.util.Map;
  
  /**
   * 处理spring security默认是以getParameter 获取参数的,而且前端是已application/json传输参数的，所以
   * 这里需要重新UsernamePasswordAuthenticationFilter
   *
   * @author bright
   */
  public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
      @Override
      public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
          if (request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)
                  || request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
              ObjectMapper mapper = new ObjectMapper();
              UsernamePasswordAuthenticationToken authRequest = null;
              try (InputStream is = request.getInputStream()) {
                  Map<String, String> authenticationBean = mapper.readValue(is, Map.class);
                  authRequest = new UsernamePasswordAuthenticationToken(
                          authenticationBean.get("username"), authenticationBean.get("password"));
              } catch (IOException e) {
                  e.printStackTrace();
                  authRequest = new UsernamePasswordAuthenticationToken(
                          "", "");
              } finally {
                  setDetails(request, authRequest);
                  return this.getAuthenticationManager().authenticate(authRequest);
              }
          } else {
              return super.attemptAuthentication(request, response);
          }
      }
  }
  