当前位置: 代码迷 >> 综合 >> Spring Security——认证失败时获取认证信息(用户名、密码、IP、SESSIONID)
  详细解决方案

Spring Security——认证失败时获取认证信息(用户名、密码、IP、SESSIONID)

热度:58   发布时间:2024-02-05 12:49:33.0

源代码 

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从登录失败中获取用户名?

 

  相关解决方案