实现记住我

This commit is contained in:
NagoColer 2023-04-10 20:39:28 +08:00
parent 18f5fc9661
commit 7169bef83a

View File

@ -16,10 +16,13 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import javax.sql.DataSource;
import java.io.IOException;
@Configuration
@ -29,8 +32,12 @@ public class SecurityConfiguration {
@Resource
AuthorizeService authorizeService;
@Resource
DataSource dataSource;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
public SecurityFilterChain filterChain(HttpSecurity http,
PersistentTokenRepository repository) throws Exception {
return http
.authorizeHttpRequests()
.anyRequest().authenticated()
@ -44,6 +51,11 @@ public class SecurityConfiguration {
.logoutUrl("/api/auth/logout")
.logoutSuccessHandler(this::onAuthenticationSuccess)
.and()
.rememberMe()
.rememberMeParameter("remember")
.tokenRepository(repository)
.tokenValiditySeconds(3600 * 24 * 7)
.and()
.csrf()
.disable()
.cors()
@ -55,6 +67,14 @@ public class SecurityConfiguration {
.build();
}
@Bean
public PersistentTokenRepository tokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
jdbcTokenRepository.setCreateTableOnStartup(false);
return jdbcTokenRepository;
}
private CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration cors = new CorsConfiguration();
cors.addAllowedOriginPattern("*");