Stud_movingj 2019-12-28 03:00 采纳率: 100%
浏览 2281
已采纳

Spring Security为什么LogoutHandler获取不到authentication

我想实现用户退出登录的时候进行日志记录(操作数据库中的登出记录表),然后自定义退出登录logout,自己实现了一个LogoutHandler,但LogoutHandler中logout函数的authentication始终获取不到,不知道为什么

@Component
public class MyLogoutHandler implements LogoutHandler
{
    String username;
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
    {
        System.out.println("进入MyLogoutHandler");
        if(authentication != null)
        {
            username = SecurityUtils.getUsername(authentication);
            System.out.println("获得当前登录用户名:"+username);
            //...操作数据库的代码省略
        }
        else
        {
            System.out.println("authentication is null");
            return;
        }

    }

}

下面是WebSecurityConfigurerAdapter中的部分代码

@Override
    protected void configure(HttpSecurity http) throws Exception {
        // 禁用 csrf, 由于使用的是JWT,我们这里不需要csrf
        http.cors().and().csrf().disable()
            .authorizeRequests()
            // 跨域预检请求
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            // web jars
            .antMatchers("/webjars/**").permitAll()
            // 查看SQL监控(druid)
            .antMatchers("/druid/**").permitAll()
            // 首页和登录页面
            .antMatchers("/").permitAll()
            .antMatchers("/login").permitAll()
            // swagger
            .antMatchers("/swagger-ui.html").permitAll()
            .antMatchers("/doc.html").permitAll()
            .antMatchers("/swagger-resources/**").permitAll()
            .antMatchers("/v2/api-docs").permitAll()
            .antMatchers("/webjars/springfox-swagger-ui/**").permitAll()
            // 验证码
            .antMatchers("/captcha.jpg**").permitAll()
            // 服务监控
            .antMatchers("/actuator/**").permitAll()
            // 其他所有请求需要身份认证
            .anyRequest().authenticated();
        http.headers().frameOptions().disable();
        // 退出登录处理器
        http.logout().logoutUrl("/logout").addLogoutHandler(myLogoutHandler);
        // token验证过滤器
        http.addFilterBefore(new JwtAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
    }

点击登录按钮之后,转跳到/logout
但控制台一直输出authentication is null,后来我又换成了继承LogoutSuccessHandler,依旧是获取不了当前用户authentication,但我在其他非退出登录的操作中获取authentication是正常的

也尝试了添加.antMatchers("/logout").permitAll()

另外我想问一下大家,还有什么比较好的办法在用户退出登录的时候记录日志,最好能做到用户主动点击退出登录和session自动失效都能记录日志

  • 写回答

3条回答

  • zqbnqsdsmd 2019-12-28 13:56
    关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥30 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题