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

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

spring security给该controller的login方法授权

@Override
  protected void configure(HttpSecurity http) throws Exception {
    http.formLogin()
        // 先进controller中去
        .loginPage("/user/auth")
        // 指定自定义登录页面
        .loginPage("/login.html")
        // 登录url
        .loginProcessingUrl("/auth/login")
        .and()
        .authorizeRequests()
        // 该controller需要授权
        .antMatchers("/user/auth").permitAll()
        // 添加一个url匹配器,如果匹配到login.html,就授权
        .antMatchers("/login.html").permitAll()
        .anyRequest()
        .authenticated()
        .and()
        // 关闭spring security默认的防csrf攻击
        .csrf().disable();
  }

这样子就行了!!! 

2. 自定义登录成功处理(返回json)

(1)实现AuthenticationSuccessHandler.java

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
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 MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
  @Autowired
  private ObjectMapper objectMapper;
  /**
   * Called when a user has been successfully authenticated.
   * @param request
   * @param response
   * @param authentication
   * @throws IOException
   * @throws ServletException
   */
  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    log.info("登录成功!!!");
    // 将登录成功的信息写到前端
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.getWriter().write(objectMapper.writeValueAsString(authentication));

  }
}

(2)修改security配置类

@Autowired
  private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.formLogin()
        // 先进controller中去
        .loginPage("/user/auth")
        // 指定自定义登录页面
        .loginPage("/login.html")
        // 登录url
        .loginProcessingUrl("/auth/login")
        .successHandler(myAuthenticationSuccessHandler)
        .and()
        .authorizeRequests()
        // 该controller需要授权
        .antMatchers("/user/auth").permitAll()
        // 添加一个url匹配器,如果匹配到login.html,就授权
        .antMatchers("/login.html").permitAll()
        .anyRequest()
        .authenticated()
        .and()
        // 关闭spring security默认的防csrf攻击
        .csrf().disable();
  }