简体   繁体   中英

How to redirect login after expire session time? -Grails 4.x

I want to redirect login/auth when session time expired. How can I do that? Also I wanna set custom session time, like 1 min, 2 min etc. Thanks

I'm using Spring-security 4.x and Grails 4.x

grails-app/src/session

Custom class

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .logout(logout -> logout
                        .logoutUrl("/logout")
                        .logoutSuccessUrl("/login/auth")
                        .invalidateHttpSession(true)
                );
    }
}

After session expiration, for new requests Spring will redirect the browser to login page("/login") by default, but if you want to change the login path (like "/my_custom_login"), I think here is a solution for that.

And for customizing session expiration time, you can implement a session listener like this:

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListener implements HttpSessionListener {

private int sessionExp_socconds=30;

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

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

Then you should define it as a bean in your SecurityConfiguration class:

@Bean
public HttpSessionListener getHttpSessionListener(){
    return new SessionListener();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM