Search code examples
mongodbspring-mvcspring-securityremember-me

Spring remember-me with MongoDB does not delete tokens


I followed this tutorial to implement remember-me functionality with MongoDB.

The tokens are saved in the database when i click the rememberme checkbox in the login page. If i delete the db entry manually and the cookie JSESSIONID maxage has expired i am getting logged out and if the JSESSIONID has expired and the remember-me cookie does not, i am still logged in which is great.

All works well but i have a question. The removeUserTokens function is never called, should i manually delete the token entry from the database? If yes where should i implement this?

Thank you.


Solution

  • After searching it a bit more i found that when i logout and having this to my configuration:

    http.authorizeRequests().antMatchers("/signup", "/about").permitAll().antMatchers("/doctor/**")
                .hasRole("DOCTOR").anyRequest().authenticated().and().rememberMe().rememberMeParameter("remember-me")
                .tokenRepository(tokenRepository).tokenValiditySeconds(1209600).and().formLogin().loginPage("/login")
                .failureUrl("/login?error=true").permitAll().and().logout().logoutUrl("/logout")
                .deleteCookies("JSESSIONID").invalidateHttpSession(true).logoutSuccessUrl("/login").permitAll();....
    

    the removeUserTokens method is called and the associated token is deleted from the db. I think the trick is made by:

    .logout().logoutUrl("/logout")
                .deleteCookies("JSESSIONID").invalidateHttpSession(true)
    

    Also as notionquest said above i added a Spring cron job to run every Friday at 3 AM in case of something is left in the db.

    @Scheduled(cron = "0 0 3 * * FRI")
    public void doScheduledWork() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.WEEK_OF_MONTH, -2);
    
        tokenRepository.deleteBeforeDated(calendar.getTime());
        logger.info("INFO", "Cron job runed at " + new Date() + " until " + calendar.getTime() + " !");
    }