Faced the following problem: when you try to delete the JSESSIONID or restart the browser, the next request to the server resets the remember-me Cookie and does not confirm the session.
http
.authenticationManager(authManager(http))
.authorizeHttpRequests()
.requestMatchers("/auth/sendCode", "/login").permitAll()
.requestMatchers("/api/*").hasAuthority("USER")
.anyRequest()
.authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
.and()
.formLogin().passwordParameter("code").usernameParameter("email")
.successHandler((request, response, authentication) -> {
response.setStatus(HttpServletResponse.SC_OK);
}).failureHandler((request, response, exception) -> response.setStatus(HttpServletResponse.SC_UNAUTHORIZED))
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/")
.deleteCookies("JSESSIONID")
.and()
.rememberMe() .tokenRepository(persistentTokenRepository())
.userDetailsService(userDetailsService())
.alwaysRemember(true)
.tokenValiditySeconds(24*60*60*14)
.key("Mykey");
return http.build();
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
return tokenRepository;
}
When requested from any of the authorized user paths, a 401 is returned from exceptionHandling(). There are two Set-Cookies in a row in the response headers:
Set-Cookie: remember-me=; Max-Age=0; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/
Set-Cookie: remember-me=aFRLMWhLYkhmNzVLMWh6M2I0b2ZYQSUzRCUzRDo2Snd1ZWFkcTFZRGlzZXp4RjAwRHlBJTNEJTNE; Max-Age=1209600; Expires=Thu, 29-Jun-2023 23:40:17 GMT; Path=/; HttpOnly
There is a table in the database and every time a new remember-me token is created: persistent table
It is necessary that the cookie is not reset and works all the time tokenValiditySeconds. Please, tell me what could be the problem?
The problem was solved like this: UserDetailsService uses a request to the repository, looking for a user by email. Spring was passing the decrypted email correctly, but adding a line break.
So far I've replaced this:
repo.findByEmail(email.replaceAll("\n","")
After that, the user became located, the session was confirmed. I'll see where the line wrapping came from and, if anything, I'll supplement the answer.