Spring Security 初始化
- 导入依赖
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>6.1.1</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>6.1.1</version> </dependency>
|
- 创建
SecurityInitializer
package com.example.init public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer { }
|
- 创建配置类
package com.example.config @Configuration @EnableWebSecurity public class SecurityConfiguration { }
|
MainInitializer
添加配置文件
@Override protected Class<?>[] getRootConfigClasses() { return new Class[]{MainConfiguration.class, SecurityConfiguration.class}; }
|
Post表单认证
在POST请求中需要携带页面中的csrfToken,否则一律进行拦截操作
<input type="text" th:id="${_csrf.getParameterName()}" th:value="${_csrf.token}" hidden>
|
密码加密
@Configuration @EnableWebSecurity public class SecurityConfiguration { @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }
|
使用
encoder.encode(yourPassword);
|
关闭CSFR
@Configuration @EnableWebSecurity public class SecurityConfiguration {
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .csfr(conf -> { conf.disable(); }) } }
|
自定义登录页
@Configuration @EnableWebSecurity public class SecurityConfiguration {
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .authorizeHttpRequests(auth -> { auth.anyRequest().authenticated(); }) .formLogin(conf -> { conf.loginPage("/login"); conf.loginProcessingUrl("/doLogin"); conf.defaultSuccessUrl("/"); conf.permitAll(); conf.usernameParameter("username"); conf.passwordParameter("password"); }) .logout(conf -> { ... }) .build(); } }
|
记住密码
@Configuration @EnableWebSecurity public class SecurityConfiguration {
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .rememberMe(conf -> { conf.alwaysRemember(false); })
|