package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
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.stereotype.Repository;
import javax.sql.DataSource;
//开启WebSecurity相关功能
@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = "com.example")
public class SecurityConfiguration {
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public PersistentTokenRepository tokenRepository(DataSource dataSource){
JdbcTokenRepositoryImpl repository = new JdbcTokenRepositoryImpl();
repository.setDataSource(dataSource);
repository.setCreateTableOnStartup(true);
return repository;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, PersistentTokenRepository repository) throws Exception {
return http.authorizeHttpRequests(auth->{
auth.requestMatchers("/static/**").permitAll();
auth.anyRequest();
})
.formLogin(conf->{
conf.loginPage("/login");
conf.loginProcessingUrl("/doLogin");
conf.defaultSuccessUrl("/");
conf.permitAll();
})
.csrf(AbstractHttpConfigurer::disable)
.rememberMe(conf->{
conf.tokenRepository(repository);
conf.tokenValiditySeconds(3600*24*7);
})
.build();
}
}
这是我SecurityConfiguration的代码,全部使用注解开发的 |