Spring Security 认证成功 AuthenticationSuccessEvent多次调用问题

在使用Spring Security Oauth2的使用,需要在认证成功执行一些日志记录和更新的操作,所以就使用了AuthenticationSuccessEvent来进行认证成功的回调。遇到了token校验也会触发的问题也解决了,然而在每次认证请求中多次调用的问题依然没有具体的思路,而且对Spring事件监听基本上没有使用过,为了防止多次执行event 就想了一些歪点子。

@Component
public class ApplicationListenerAuthencationSuccess implements ApplicationListener<AuthenticationSuccessEvent> {
    @Autowired
    private UserLoginRecordService userLoginRecordService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserServiceImpl userService;

    private ThreadLocal<Integer> tl = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };
    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        if (tl.get().intValue() <= 0) {
        //下面的判断是为了保证只有认证的时候才会执行记录日志的操作,token校验剔除
            if (event.getSource().getClass().getName().equals("org.springframework.security.authentication.UsernamePasswordAuthenticationToken")) {
                String username = request.getParameter("username");
                //其他操作
                tl.set(1);
            }
        }else {
            tl.remove();
        }
    }
}

也尝试过其他方法去进行认证成功的回调但是没有成功。。。
吐槽一下:我是真的没想到,学了那么久的ThreadLocal,第一次用到这歪魔邪道上。
如果有什么好的解决办法:包括其他方式认证回调或者其他方法解决可以私信或留言= = 万分感谢!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可能是因为您的 Spring Security 配置不正确,导致认证成功后无法访问您想要的页面。 以下是一些可能的原因和解决方法: 1. 没有配置正确的访问控制规则 您需要在 Spring Security 配置中添加正确的访问控制规则,以允许认证成功后访问您想要的页面。例如: ``` http.authorizeRequests() .antMatchers("/login").permitAll() .antMatchers("/secure/**").authenticated() .anyRequest().permitAll() .and().formLogin().loginPage("/login").defaultSuccessURL("/secure/dashboard"); ``` 在这个例子中,我们允许所有用户访问 `/login` 页面,但需要认证才能访问 `/secure/**` 下的所有页面。认证成功后,用户将被重定向到 `/secure/dashboard` 页面。 2. 没有正确配置登录成功后的页面 如果您没有在 Spring Security 配置中正确配置登录成功后的页面,可能会导致认证成功后请求 404。您需要在配置中添加 `defaultSuccessURL`,以指定用户成功登录后要重定向到的页面。例如: ``` http.formLogin() .loginPage("/login") .defaultSuccessURL("/secure/dashboard") .permitAll(); ``` 在这个例子中,我们在登录页面上设置 `defaultSuccessURL`,以确保用户成功登录后被重定向到 `/secure/dashboard` 页面。 3. 没有正确配置错误页面 如果您没有在 Spring Security 配置中正确配置错误页面,可能会导致认证成功后请求 404。您需要在配置中添加 `failureUrl`,以指定用户在登录失败后要重定向到的页面。例如: ``` http.formLogin() .loginPage("/login") .defaultSuccessURL("/secure/dashboard") .failureUrl("/login?error=true") .permitAll(); ``` 在这个例子中,我们在登录页面上设置 `failureUrl`,以确保用户在登录失败后被重定向到 `/login?error=true` 页面。 如果您仍然无法解决问题,请检查您的 Spring Security 配置是否正确,并确保您的代码没有其他错误。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值