spring-security中使用自定义处理器时出现的问题

本文探讨了在spring-security中自定义处理器处理用户登录时遇到的问题。当尝试从Authentication对象中获取Principal的username时,出现错误,但业务逻辑仍能正常运行。错误信息未显示,而使用request对象则无此问题。作者寻求对spring-security底层有深入了解的专家提供指导,分享了登录校验和信息存储的代码片段。
摘要由CSDN通过智能技术生成

spring-security中自定义处理器的使用

故障代码:

//自定义处理器,继承SimpleUrlAuthenticationSuccessHandler重写onAuthenticationSuccess
@Component
public class AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Autowired
    private UserDao userDao;
    /**
     * 登录成功执行的方法
     *
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //通过authentication获取当前登录用户名,**故障点**
        //User user = (User) authentication.getPrincipal();
        //String username = user.getUsername();

        //通过request获取当前登录用户名
        String username = request.getParameter("username");
        System.out.println(username);

        //根据用户名查询上次一登录信息
        UserLoginLog lastLoginLog = userDao.findLoginLogByUsername(username);
        System.out.println(lastLoginLog);

        //将用户的上次登录信息放入session中供前台获取
        request.getSession().setAttribute("lastLogin", lastLoginLog);


        //将本地登录的用户名,登录ip,登录时间封装,交给dao写入数据库
        String dateToStr = DateUtil.formatDateToStr(new Date());
        UserLoginLog userLoginLog = new UserLoginLog(username, request.getRemoteAddr(), dateToStr);
        userDao.addUserLoginLog(userLoginLog);

        super.onAuthenticationSuccess(request, response, authentication);
    }

}

这是一个用户登陆成功的自定义处理器,业务逻辑为登录校验成功后,查询该用户的用户名、上次登录的时间、上次登录ip,然后将查询结果封装返回前台。 最后把本次登录信息写入数据库。

问题:使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值