How to enable session and set session timeout in Spring Security

后端 未结 5 2197
轮回少年
轮回少年 2020-12-14 00:53

I am new to Spring Security and I am working on a login, logout, and session timeout feature. I have configured my code by referring to this document. My code looks below:

5条回答
  •  再見小時候
    2020-12-14 01:42

    Different ways to configure session timeout time(maxInactiveInterval) in spring security.

    1. By addinng session config in web.xml(from raju vaishnav's answer)

    2. By creating implementation of HttpSessionListener and adding it to servlet context.(from munilvc's answer)

    3. By registering your custom AuthenticationSuccessHandler in spring security configuration, and setting session maximum inactive interval in onAuthenticationSuccess method.

    This implementation has advantages

    1. On login success, You can set different value of maxInactiveInterval for different roles/users.

    2. On login success, you can set user object in session, hence user object can be accessed in any controller from session.

    Disadvantage: You can not set session timeout for ANONYMOUS user(Un-authenticated user)

    Create AuthenticationSuccessHandler Handler

    public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler
    {
    
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
                throws IOException 
        {
            Set roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
            if (roles.contains("ROLE_ADMIN"))
            {
                request.getSession(false).setMaxInactiveInterval(60);
            }
            else
            {
                request.getSession(false).setMaxInactiveInterval(120);
            }
            //Your login success url goes here, currently login success url="/"
            response.sendRedirect(request.getContextPath());
        }
    }
    

    Register success handler

    In Java Config way

    @Override
    protected void configure(final HttpSecurity http) throws Exception
    {
        http
            .authorizeRequests()
                .antMatchers("/resources/**", "/login"").permitAll()
                .antMatchers("/app/admin/*").hasRole("ADMIN")
                .antMatchers("/app/user/*", "/").hasAnyRole("ADMIN", "USER")
            .and().exceptionHandling().accessDeniedPage("/403")
            .and().formLogin()
                .loginPage("/login").usernameParameter("userName")
                .passwordParameter("password")
                .successHandler(new MyAuthenticationSuccessHandler())
                .failureUrl("/login?error=true")
            .and().logout()
                .logoutSuccessHandler(new CustomLogoutSuccessHandler())
                .invalidateHttpSession(true)
            .and().csrf().disable();
    
        http.sessionManagement().maximumSessions(1).expiredUrl("/login?expired=true");
    }
    

    In xml config way

    
        
    
        
        
    
        
        
        
    
        
    
        
    
        
    
        
            
        
     
    
     
    
    

    Working code is available in my github repository Working code is available in two forms

    1. XML config way of implementation

    2. JAVA config way of implementation

    If you want to have automatic logout feature and timer which displays when session is about to expire, if user is filling form but not submitted then user can extend session by clicking on keep session alive button. If you want to implement auto logout refer stack overflow answer on auto logout on session timeout. Hope this will help.

提交回复
热议问题