前后端分离 Spring Security 对登出.logout()的处理

Posted As_zyh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前后端分离 Spring Security 对登出.logout()的处理相关的知识,希望对你有一定的参考价值。

前端axios发出的post请求如下

    logout() 
      this.axios.post(this.tools.serverAddr+'/logout')
          .then(function () 
            this.$message(
              message: "注销成功",
              type: 'success',
              duration: 1000
            );
            this.$router.replace(path: '/login');
          .bind(this))
          .catch(function (err) 
            if (err.response) 
              console.log(err.response)
            
          .bind(this))
    ,

后端spring security默认将/logout重定向到/login?logout,在前后端分离项目中会出现跨域请求问题

需要自定义对登出的处理

.logout()
//注销成功的处理
.logoutSuccessHandler(new LogoutSuccessHandler() 
	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException 
		printCode(response, 4);
	
)

WebSecurityConfig中configure(HttpSecurity http)的完整代码如下

//方法注解方式
    @Override
    protected void configure(HttpSecurity http) throws Exception 
        http.formLogin()
                .loginProcessingUrl("/doLogin")
                .successHandler(new AuthenticationSuccessHandler() 
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException 
                        printCode(httpServletResponse, 1);
                    
                )
                .failureHandler(new AuthenticationFailureHandler() 
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException 
                        printCode(httpServletResponse, 2);
                    
                )
                .permitAll()
                .and()
                .logout()
                //注销成功的处理
                .logoutSuccessHandler(new LogoutSuccessHandler() 
                    @Override
                    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException 
                        printCode(response, 4);
                    
                )
                .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/sysUser/currentUser").permitAll()

                //下面三行放开测试接口的权限,生产环境一定要删掉
                .and()
                .authorizeRequests()
                .antMatchers("/emp","/dep","/sysUser","/sysRole","/sysPermission").permitAll()

                .anyRequest().authenticated()
                .and()
                .exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() 
                    @Override
                    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException 
                        printCode(httpServletResponse, 3);
                    
                )
                .and().headers().frameOptions().sameOrigin()
                // .and().cors()
                .and().csrf().disable();
    

printCode方法如下

private void printCode(HttpServletResponse httpServletResponse, Integer code) 
        try 
            httpServletResponse.setCharacterEncoding("UTF-8");
            PrintWriter out = httpServletResponse.getWriter();
            ServerResponse sr = new ServerResponse<>();
            sr.setCode(code);
            ObjectMapper mapper = new ObjectMapper();
            String str = mapper.writeValueAsString(sr);
            out.write(str);
            out.close();
         catch (UnsupportedEncodingException e) 
            e.printStackTrace();
         catch (JsonProcessingException e) 
            e.printStackTrace();
         catch (IOException e) 
            e.printStackTrace();
        
    

ServerResponse类代码如下

public class ServerResponse<T> implements Serializable 
    private Integer code;//0 未登录 1 登录成功  2登录失败 4登出成功
    private Long total;//查询出来的总记录数
    private T data;//查询出来的数据

    public ServerResponse() 
    

    public ServerResponse(Long total, T data) 
        this.total = total;
        this.data = data;
    

    public Integer getCode() 
        return code;
    

    public void setCode(Integer code) 
        this.code = code;
    

    public Long getTotal() 
        return total;
    

    public void setTotal(Long total) 
        this.total = total;
    

    public T getData() 
        return data;
    

    public void setData(T data) 
        this.data = data;
    

参考文献:
1.《Spring Boot+Vue开发实战》 朱建昕
2. https://www.jianshu.com/p/a061c28d8202

以上是关于前后端分离 Spring Security 对登出.logout()的处理的主要内容,如果未能解决你的问题,请参考以下文章

Spring Security-登录用户退出登录操作

Spring Security整合JWT,实现单点登录,So Easy~!

Spring Security6登录用户退出登录操作

前后端分离下spring security 跨域问题等

Spring boot+Spring security+JWT实现前后端分离登录认证及权限控制

spring boot + jwt + spring security前后端分离实现权限控制