前后端分离项目中spring security 6如何配置logoutSuccessHandler?

大家好我是图恩,在接入spring security后我们可以配置相应的过滤规则以及登录/登出接口地址,如果你的项目是前后端分离的项目,那么在配置登出接口后spring security默认重定向的地址是“/loign”,前端无法识别返回的数据从而重定向到登录页面,这个时候需要将登陆接口的返回数据改为json格式。

@Bean
    protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 禁用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
        .and()
        .authorizeHttpRequests()
        // 放行登录请求
        .requestMatchers("/account/login").permitAll()
        // 放行不需要校验用户信息接口
        .requestMatchers("/tools/*").permitAll()
        // 其他请求都要求认证
        .anyRequest().authenticated()
        .and()
        // 将退出接口映射到controller接口
        .logout().logoutUrl("/account/logout").logoutSuccessHandler(securityLogoutSuccessHandler)
        .and()
        // 允许跨域
        .csrf().disable();
        return http.build();
    }

只需要给logoutSuccessHandler方法添加对应的处理方法即可,以下代码供参考:

@Service
public class SecurityLogoutSuccessHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(200);
        response.setCharacterEncoding("utf-8");
        PrintWriter printWriter = response.getWriter();
        Map map = new HashMap();
        map.put("code",0);
        map.put("msg","注销成功");
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(map);
        printWriter.write(json);
        printWriter.flush();
        printWriter.close();
    }
}

其中最重要的一步就是通过mapper.writeValueAsString方法实现json数据的返回。

本文章由javascript技术分享原创和收集

发表评论 (审核通过后显示评论):