Spring remember-me with MongoDB 不会删除标记

Spring remember-me with MongoDB does not delete tokens

我按照 this 教程使用 MongoDB 实现了记住我的功能。

当我点击登录页面中的 rememberme 复选框时,令牌将保存在数据库中。如果我手动删除数据库条目并且 cookie JSESSIONID maxage 已过期,我将被注销,如果 JSESSIONID 已过期而 remember-me cookie 没有,我仍然登录,这很好。

一切正常,但我有一个问题。永远不会调用 removeUserTokens 函数,我应该从数据库中手动删除令牌条目吗?如果是,我应该在哪里实施?

谢谢。

必须根据 Java doc.

手动删除(例如通过批处理)

PersistentTokenBasedRememberMeServices

Note that while this class will use the date a token was created to check whether a presented cookie is older than the configured tokenValiditySeconds property and deny authentication in this case, it will not delete these tokens from storage. A suitable batch process should be run periodically to remove expired tokens from the database.

PersistentTokenBasedRememberMeServices 用来存储用户持久登录令牌的抽象 (PersistentTokenRepository)。

进一步搜索后,我发现当我注销并将其添加到我的配置中时:

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();....

调用了 removeUserTokens 方法并从数据库中删除了关联的令牌。我认为这个技巧是由:

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

此外,正如上面所说的 notionquest,我在每个星期五凌晨 3 点向 运行 添加了一个 Spring cron 作业,以防数据库中遗留某些内容。

@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() + " !");
}