2016-04-22 13 views
14

Xin chào, tôi là người mới sử dụng Bảo mật mùa xuân, tôi đang làm việc trên tính năng đăng nhập, đăng xuất và hết giờ phiên. Tôi đã định cấu hình mã của mình bằng cách giới thiệu tài liệu this, mã của tôi trông bên dưới.Cách bật thời gian chờ phiên và đặt phiên trong Spring Security

@Override 
    protected void configure(HttpSecurity http) throws Exception { 

     http.authorizeRequests().antMatchers("/admin/**") 
      .access("hasRole('ROLE_USER')").and().formLogin() 
      .loginPage("/login").failureUrl("/login?error") 
       .usernameParameter("username") 
       .passwordParameter("password") 
       .and().logout().logoutSuccessUrl("/login?logout").and().csrf(); 
     http.sessionManagement().maximumSessions(1).expiredUrl("/login?expired"); 
    } 

Override lớp AbstractSecurityWebApplicationInitializer

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; 

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer { 

    @Override 
    public boolean enableHttpSessionEventPublisher() { 
    return true; 
} 

} 

Tuy nhiên tôi cần phải làm rõ cho dù tôi đang làm đúng, nếu nó có vẻ tốt thì nơi nào tôi cần phải thời gian chờ phiên thiết lập. Tôi đang làm nó hoàn toàn dựa trên chú thích.

Trả lời

6

Tôi đã có thể giải quyết vấn đề trên bằng cách chỉ thêm cấu hình bên dưới vào tệp web.xml. bất kỳ cách nào tốt hơn sẽ được chấp nhận.

<session-config> 
    <session-timeout>20</session-timeout> 
</session-config> 
9

Nếu bạn đang sử dụng JavaConfig và không muốn sử dụng XML, bạn có thể tạo ra một HttpSessionListener và sử dụng getSession().setMaxInactiveInterval(), sau đó trong Initializer thêm người nghe trong onStartup():

public class SessionListener implements HttpSessionListener { 

    @Override 
    public void sessionCreated(HttpSessionEvent event) { 
     System.out.println("session created"); 
     event.getSession().setMaxInactiveInterval(15); 
    } 

    @Override 
    public void sessionDestroyed(HttpSessionEvent event) { 
     System.out.println("session destroyed"); 
    } 
} 

Sau đó, trong Initializer:

@Override 
public void onStartup(ServletContext servletContext) throws ServletException { 
    super.onStartup(servletContext); 
    servletContext.addListener(new SessionListener()); 
} 
+0

Bạn cũng có thể thêm người nghe làm hạt, trong trường hợp bạn khởi động ứng dụng theo cách khác. – Alic

+0

super.onStartup (servletContext); của nó không tham gia hiển thị lỗi trong intializer – jeevanswamy21

Các vấn đề liên quan