三、spring security【安全配置】
安全配置
- pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- 配置默认的账号密码
spring.security.user.name=user
spring.security.user.password=123456
- 添加HttSecurity配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity(debug = true) // 开启调试模式,生产环境不要使用
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((req) ->
req.antMatchers("/api/**").authenticated() // 指定需要认证才能访问的URL
)
.httpBasic(Customizer.withDefaults())
.formLogin(form->form.loginPage("/")) // 定义登陆页面
.csrf().disable();// 禁用csrf
// ...
return http.build();
}
}
- 添加WebSecurity配置,放行不需要认证的URL
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
/**
* 放行不需要认证的URL
* @return
*/
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().antMatchers("/api/say");
}
- 页面模拟请求
请求1:GET /api/say 无条件反行
请求2:POST /api/say2 未登录,受到拦截,登录后可访问
扩展
在Spring Security 5.4版本之后,官方建议的配置、包括前后版本的配置对比
tip: Spring Security 5.4.x 对应 spring boot 2.4.x
- 在 Spring Security 5.4 中,我们引入了通过创建 SecurityFilterChain bean 来配置 HttpSecurity 的能力,而原来的继承WebSecurityConfigurerAdapter 已不建议使用
@Configuration
public class SecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authz) -> authz
.anyRequest().authenticated()
)
.httpBasic(withDefaults());
return http.build();
}
}
- 配置WebSecurity,推荐的做法是注册一个 WebSecurityCustomizer bean:
@Configuration
public class SecurityConfiguration {
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().antMatchers("/ignore1", "/ignore2");
}
}

浙公网安备 33010602011771号