大家好我是图恩,在接入spring security后我们可以配置相应的过滤规则以及登录/登出接口地址,如果你的项目是前后端分离的项目,那么在配置登出接口后spring security默认重定向的地址是“/loign”,前端无法识别返回的数据从而重定向到登录页面,这个时候需要将登陆接口的返回数据改为json格式。
@Bean\n protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {\n\n http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);\n // 禁用session\n http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)\n .and()\n .authorizeHttpRequests()\n // 放行登录请求\n .requestMatchers("/account/login").permitAll()\n // 放行不需要校验用户信息接口\n .requestMatchers("/tools/*").permitAll()\n // 其他请求都要求认证\n .anyRequest().authenticated()\n .and()\n // 将退出接口映射到controller接口\n .logout().logoutUrl("/account/logout").logoutSuccessHandler(securityLogoutSuccessHandler)\n .and()\n // 允许跨域\n .csrf().disable();\n return http.build();\n }只需要给logoutSuccessHandler方法添加对应的处理方法即可,以下代码供参考:
@Service\npublic class SecurityLogoutSuccessHandler implements LogoutSuccessHandler {\n @Override\n public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {\n response.setContentType("application/json;charset=utf-8");\n response.setStatus(200);\n response.setCharacterEncoding("utf-8");\n PrintWriter printWriter = response.getWriter();\n Map map = new HashMap();\n map.put("code",0);\n map.put("msg","注销成功");\n ObjectMapper mapper = new ObjectMapper();\n String json = mapper.writeValueAsString(map);\n printWriter.write(json);\n printWriter.flush();\n printWriter.close();\n }\n}其中最重要的一步就是通过mapper.writeValueAsString方法实现json数据的返回。