前後端分離項目中 互動的往往是json 是以需要通過json告知前段登入是否成功
SpringSecurityConfig
修改SpringSecurityConfig (其他配置已經删除) 在其中配置AuthenticationFailureHandler ,AuthenticationSuccessHandler
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationFailureHandler customAuthenticationFailureHandler;
@Autowired
private AuthenticationSuccessHandler customAuthenticationSuccessHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
// 驗證碼過濾器
http.addFilterBefore(imageCodeValidateFilter, UsernamePasswordAuthenticationFilter.class)
// 跳轉前台的位址
.formLogin().loginPage("/loginPage")
// 登入調用的接口位址
.loginProcessingUrl("/login").successHandler(customAuthenticationSuccessHandler).failureHandler()
}
}
AuthenticationFailureHandler與AuthenticationSuccessHandler
主要就是實作SimpleUrlAuthenticationFailureHandler與CustomSavedRequestAwareAuthenticationSuccessHandler 接口 其餘按照樓主的配置即可
@Component("customAuthenticationFailureHandler")
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
/**
* @param exception 認證失敗時抛出異常
*/
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
String referer = request.getHeader("Referer");
logger.info("referer:" + referer);
// 如果下面有值,則認為是多端登入,直接傳回一個登入位址
Object toAuthentication = request.getAttribute("toAuthentication");
String lastUrl = toAuthentication != null ? /loginPage: StringUtils.substringBefore(referer, "?");
logger.info("上一次請求的路徑 :" + lastUrl);
super.setDefaultFailureUrl(lastUrl + "?error");
super.onAuthenticationFailure(request, response, exception);
}
}
@Component("customAuthenticationSuccessHandler")
public class CustomAuthenticationSuccessHandler extends CustomSavedRequestAwareAuthenticationSuccessHandler {
@Autowired
Utils utils;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SysUser sysUser = (SysUser)authentication.getPrincipal();
logger.info("|" + "使用者" + sysUser.getUsername() + "于" + sd.format(new Date()) + "通過web端登入系統,ip為"
+ utils.getIpAddr() + "。" + "|" + sd.format(new Date()) + "|" + sysUser.getUsername());
super.onAuthenticationSuccess(request, response, authentication);
}
}