源代码
package cn.edu.zstu.shihua.xihu.listener;import cn.edu.zstu.shihua.xihu.model.Log;
import cn.edu.zstu.shihua.xihu.service.ILogService;
import cn.edu.zstu.shihua.xihu.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;import java.time.LocalDateTime;/*** @author ShenTuZhiGang* @version 1.0.0* @date 2020-08-02 13:52*/
@Component
@Slf4j
public class AuthenticationFailureListenerimplements ApplicationListener<AbstractAuthenticationFailureEvent> {@AutowiredILogService iLogService;@Overridepublic void onApplicationEvent(AbstractAuthenticationFailureEvent event) {Object username = event.getAuthentication().getPrincipal();Object credentials = event.getAuthentication().getCredentials();Object details=event.getAuthentication().getDetails();String ip = ((WebAuthenticationDetails)details).getRemoteAddress();Log loginLog = new Log();loginLog.setOperation("登录");loginLog.setType("login");loginLog.setIp(ip);loginLog.setOperator((String)username);loginLog.setTime(LocalDateTime.now());loginLog.setStatus("failure");loginLog.setRemark("登录失败:"+event.getException().getMessage());iLogService.save(loginLog);}
}
参考文章
如何使用Spring Security从登录失败中获取用户名?