spring security cas 登出时总是会跳到session-timeout页面怎么处理?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring security cas 登出时总是会跳到session-timeout页面怎么处理?相关的知识,希望对你有一定的参考价值。

spring security cas 登出时总是会跳到session-timeout页面怎么处理?
我配置了登出: <logout invalidate-session="true" logout-success-url="/web/logout_Success.jsp" />
配置了 session管理:
<session-management invalid-session-url="/pages/session-timeout.jsp">
<concurrency-control max-sessions="1" error-if-maximum-exceeded="true" expired-url="/web/login.jsp"/>
</session-management>

因为你的cookie还在,重定向到首页后,验证cookie绑定的sessionid失效又重定向到session失效的页面。3.1以上的版本应该有 logout标签里应该有delete-cookies="",在登出时删除指定cookie。在以下的版本解决办法应该只能按照源码路径,拷贝源码,在session.invalidate()的后面加上cookie失效的代码 如:
Cookie cookie = new Cookie("JSESSIONID", null);
cookie.setPath(request.getContextPath()==""?"/":request.getContextPath());
cookie.setMaxAge(0);
response.addCookie(cookie);
参考技术A

你退出之前在cas server上退出了吗?

<custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER" />


<bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter"
p:filterProcessesUrl="/j_spring_cas_security_logout">
<constructor-arg value="https://$cas.server.host/cas/logout" />
<constructor-arg>
<bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" />
</constructor-arg>
</bean>

前后端分离 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 cas 登出时总是会跳到session-timeout页面怎么处理?的主要内容,如果未能解决你的问题,请参考以下文章

Spring security CAS SSO 每次询问登录凭据时

CAS 6.0 和 Spring Security:服务票证验证时 JWT 配置失败

Spring-security-cas 插件单点注销不起作用

Grails Spring Security 和 CAS 问题

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

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