如何在Spring Security中启用会话和设置会话超时

raj*_*nav 24 java session spring spring-mvc spring-security

嗨,我是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");
}
Run Code Online (Sandbox Code Playgroud)

重写AbstractSecurityWebApplicationInitializer类

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

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

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

}
Run Code Online (Sandbox Code Playgroud)

我还需要澄清我是否正确,如果它看起来不错,那么我需要在哪里设置会话超时.我是基于注释完全做到的.

mun*_*lvc 26

如果您正在使用JavaConfig并且不想使用XML ,则可以创建HttpSessionListener并使用getSession().setMaxInactiveInterval(),然后在Initializer添加侦听器中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");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在初始化程序中:

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    super.onStartup(servletContext);
    servletContext.addListener(new SessionListener());
}
Run Code Online (Sandbox Code Playgroud)

  • 我应该在哪个类中使用 void onStartup 函数 (3认同)
  • 您还可以将侦听器添加为 bean,以防您以不同方式启动应用程序。 (2认同)

raj*_*nav 14

我只能通过在web.xml中添加以下配置来解决上述问题.任何更好的方式都会被接受.

 <session-config>
    <session-timeout>20</session-timeout>
</session-config>
Run Code Online (Sandbox Code Playgroud)


JJ *_*man 9

使用application.properties时,set属性server.session.timeout=值以秒为单位.

  • `server.servlet.session.timeout =`帮助了我。常用属性列表:https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html (5认同)

Pra*_*ngi 9

Spring Security 中配置会话超时时间(maxInactiveInterval)的不同方式。

1. 通过在 web.xml 中添加会话配置(来自 raju vaishnav 的回答)

2. 通过创建 HttpSessionListener 的实现并将其添加到 servlet 上下文。(来自 munilvc 的回答)

3. 通过在 spring 安全配置中注册您的自定义 AuthenticationSuccessHandler ,并在 onAuthenticationSuccess 方法中设置会话最大非活动间隔。

这种实现有优势

  1. 登录成功后,您可以为不同的角色/用户设置不同的 maxInactiveInterval 值。

  2. 登录成功后,您可以在会话中设置用户对象,因此可以在任何控制器中从会话访问用户对象。

缺点:不能为匿名用户(未经身份验证的用户)设置会话超时

创建 AuthenticationSuccessHandler 处理程序

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler
{

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException 
    {
        Set<String> 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());
    }
}
Run Code Online (Sandbox Code Playgroud)

注册成功处理程序

以 Java Config 方式

@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");
}
Run Code Online (Sandbox Code Playgroud)

以xml配置方式

<http auto-config="true" use-expressions="true" create-session="ifRequired">
    <csrf disabled="true"/>

    <intercept-url pattern="/resources/**" access="permitAll" />
    <intercept-url pattern="/login" access="permitAll" />

    <intercept-url pattern="/app/admin/*" access="hasRole('ROLE_ADMIN')" />
    <intercept-url pattern="/" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')" />
    <intercept-url pattern="/app/user/*" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')" />

    <access-denied-handler error-page="/403" />

    <form-login 
        login-page="/login"
        authentication-success-handler-ref="authenticationSuccessHandler"
        authentication-failure-url="/login?error=true" 
        username-parameter="userName"
        password-parameter="password" />

    <logout invalidate-session="false" success-handler-ref="customLogoutSuccessHandler"/>

    <session-management invalid-session-url="/login?expired=true">
        <concurrency-control max-sessions="1" />
    </session-management>
 </http>

 <beans:bean id="authenticationSuccessHandler" class="com.pvn.mvctiles.configuration.MyAuthenticationSuccessHandler" />

Run Code Online (Sandbox Code Playgroud)

工作代码在我的 github 存储库 中可用工作代码有两种形式

1. XML config 实现方式

2. JAVA config的实现方式

如果您想要自动注销功能和在会话即将到期时显示的计时器,如果用户正在填写表单但未提交,则用户可以通过单击保持会话活动按钮来扩展会话。如果你想实现自动注销,请参考stack overflow answer on auto logout on session timeout。希望这会有所帮助。


小智 7

在您的应用程序属性中使用 server.servlet.session.timeout=1m(如果未指定持续时间后缀,则将使用秒。)

默认为 30 分钟。