Java 如何在 Spring Security 中启用会话和设置会话超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36795678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to enable session and set session timeout in Spring Security
提问by raju vaishnav
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 thisdocument. My code looks below:
我是 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 the class AbstractSecurityWebApplicationInitializer
覆盖类 AbstractSecurityWebApplicationInitializer
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
@Override
public boolean enableHttpSessionEventPublisher() {
return true;
}
}
I need clarification on whether I am doing it right, if it looks good, then where I need to setup the session timeout. I am doing it fully based on annotation.
我需要澄清我是否做得对,如果看起来不错,那么我需要在哪里设置会话超时。我完全基于注释来做。
采纳答案by raju vaishnav
I was able to solve above issue by adding below config in web.xml only. any better way will be accepted.
我只能通过在 web.xml 中添加以下配置来解决上述问题。任何更好的方式都会被接受。
<session-config>
<session-timeout>20</session-timeout>
</session-config>
回答by munilvc
If you are using JavaConfigand do not want to use XML you can create a HttpSessionListener
and use getSession().setMaxInactiveInterval()
, then in the Initializer
add the listener in onStartup()
:
如果您正在使用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");
}
}
Then in the Initializer:
然后在初始化程序中:
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addListener(new SessionListener());
}
回答by JJ Roman
When using application.properties set property server.session.timeout=
value is in seconds.
使用 application.properties 时设置的属性server.session.timeout=
值以秒为单位。
回答by PraveenKumar Lalasangi
Different ways to configure session timeout time(maxInactiveInterval) in spring security.
Spring Security 中配置会话超时时间(maxInactiveInterval)的不同方式。
1. By addinng session config in web.xml(from raju vaishnav's answer)
1. 通过在 web.xml 中添加会话配置(来自 raju vaishnav 的回答)
2. By creating implementation of HttpSessionListener and adding it to servlet context.(from munilvc's answer)
2. 通过创建 HttpSessionListener 的实现并将其添加到 servlet 上下文。(来自 munilvc 的回答)
3. By registering your custom AuthenticationSuccessHandler in spring security configuration, and setting session maximum inactive interval in onAuthenticationSuccess method.
3. 通过在 spring 安全配置中注册您的自定义 AuthenticationSuccessHandler ,并在 onAuthenticationSuccess 方法中设置会话最大非活动间隔。
This implementation has advantages
这种实现有优势
On login success, You can set different value of maxInactiveInterval for different roles/users.
On login success, you can set user object in session, hence user object can be accessed in any controller from session.
登录成功后,您可以为不同的角色/用户设置不同的 maxInactiveInterval 值。
登录成功后,您可以在会话中设置用户对象,因此可以在任何控制器中从会话访问用户对象。
Disadvantage: You can not set session timeout for ANONYMOUS user(Un-authenticated user)
缺点:不能为匿名用户(未经身份验证的用户)设置会话超时
Create AuthenticationSuccessHandler Handler
创建 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());
}
}
Register success handler
注册成功处理程序
In Java Config way
以 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");
}
In xml config way
以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" />
Working code is available in my github repositoryWorking code is available in two forms
工作代码在我的 github 存储库中可用工作代码有两种形式
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.
如果您想拥有自动注销功能和在会话即将到期时显示的计时器,如果用户正在填写表单但未提交,则用户可以通过单击保持会话活动按钮来扩展会话。如果你想实现自动注销,请参考stack overflow answer on auto logout on session timeout。希望这会有所帮助。