记住我 token保存到数据库
这里使用jpa+mysql
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/fly-demo?serverTimezone=UTC&useUnicode=yes&characterEncoding=UTF-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
设置配置rememberme
import javax.sql.DataSource;
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationSuccessHandler flyAuthenticationSuccessHandler;
@Autowired
private AuthenticationFailureHandler flyAuthenticationFailureHandler;
@Autowired
private SecurityProperties securityProperties;
@Autowired
private PasswordEncoder passwordEncoder;
@Bean
public PasswordEncoder setPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
private DataSource dataSource;
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
// tokenRepository.setCreateTableOnStartup(true);
tokenRepository.setDataSource(dataSource);
return tokenRepository;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
ValidateCodeFilter codeFilter = new ValidateCodeFilter(flyAuthenticationFailureHandler);
http
.addFilterBefore(codeFilter, UsernamePasswordAuthenticationFilter.class)
.formLogin()
.loginPage("/authentication/request")
.loginProcessingUrl("/authentication/form")
.successHandler(flyAuthenticationSuccessHandler)
.failureHandler(flyAuthenticationFailureHandler)
.and()
.rememberMe()
.tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(securityProperties.getBrowser().getRememberMe())
.userDetailsService(userDetails())
.and()
.authorizeRequests()
.antMatchers("/authentication/request",
securityProperties.getBrowser().getLoginPage(),
"/captcha")
.permitAll()
.anyRequest().authenticated()
.and().csrf().disable();
}
@Bean
public UserDetailsService userDetails(){
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername("user").password(passwordEncoder.encode("123")).roles("USER").build());
return manager;
}
}