Spring security自定义用户认证流程详解

2020-03-11 18:01:22王冬梅

(3)测试

说明:authentication对象中包含的信息,会因为登录方式的不同而发生改变

3.自定义登录失败处理(返回json)

  实现AuthenticationFailureHandler.java接口即可,跟登录成败处理配置一样。

4.自定义登录成功处理逻辑

 以上的登录成功或失败的返回的都是json,但是在某些情况下,就是存在着登录成功或者失败进行页面跳转(spring security默认的处理方式),那么这种返回json的方式就不合适了。所以,我们应该做得更灵活,做成可配置的。

 对于登录成功逻辑而言只需要对MyAuthenticationSuccessHandler.java稍做修改就行,代码如下所示:

/**
 * SavedRequestAwareAuthenticationSuccessHandler spring security 默认的成功处理器
 */
@Slf4j
@Component
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
  @Autowired
  private ObjectMapper objectMapper;

  /**
   * 配置的登录方式
   */
//  @Value("${xxx:默认方式}")
  private String loginType = "JSON";
  /**
   * Called when a user has been successfully authenticated.
   */
  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    log.info("登录成功!!!");

    // 如果配置的登录方式是JSON,就返回json数据
    if ("JSON".equals(loginType)) {
      // 将登录成功的信息写到前端
      response.setContentType(MediaType.APPLICATION_JSON_VALUE);
      response.getWriter().write(objectMapper.writeValueAsString(authentication));
    } else { // 否则就使用默认的跳转方式
      super.onAuthenticationSuccess(request,response,authentication);
    }
  }
}

5.自定义登录失败处理逻辑

同登录成功类似,具体代码如下:

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@Component
public class MySimpleUrlAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
  @Autowired
  private ObjectMapper objectMapper;

  /**
   * 配置的登录方式
   */
//  @Value("${xxx:默认方式}")
  private String loginType = "JSON";
  @Override
  public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
    log.info("登录失败!!!");

    // 如果配置的登录方式是JSON,就返回json数据
    if ("JSON".equals(loginType)) {
      // 将登录成功的信息写到前端
      response.setStatus(HttpStatus.UNAUTHORIZED.value());
      response.setContentType(MediaType.APPLICATION_JSON_VALUE);
      response.getWriter().write(objectMapper.writeValueAsString(exception));
    } else { // 否则就使用默认的跳转方式,跳转到一个错误页面
      super.onAuthenticationFailure(request,response,exception);
    }
  }
}