安全
本节解答了在使用 Spring Boot 时有关安全性的问题,包括在使用 Spring Security 与 Spring Boot 结合时出现的问题。
有关 Spring Security 的更多信息,请参阅 Spring Security 项目页面。
关闭 Spring Boot 安全配置
如果你在应用中定义了一个带有 @Configuration 注解的 SecurityFilterChain Bean,这个操作将会关闭 Spring Boot 中默认的 Web 应用安全设置。
更改 UserDetailsService 并添加用户账户
如果你提供了一个类型为 AuthenticationManager、AuthenticationProvider 或 UserDetailsService 的 @Bean,默认的 @Bean 用于 InMemoryUserDetailsManager 将不会被创建。这意味着你可以使用 Spring Security 的全部功能集(例如 各种认证选项)。
添加用户账户的最简单方法是提供您自己的 UserDetailsService Bean。
在代理服务器后运行启用 HTTPS
确保应用程序的所有主要端点仅通过 HTTPS 可用,是任何应用程序都需要完成的重要任务。如果你使用 Tomcat 作为 Servlet 容器,那么当 Spring Boot 检测到某些环境设置时,它会自动添加 Tomcat 自带的 RemoteIpValve,从而使你可以依赖 HttpServletRequest 来报告它是否安全(即使是在处理实际 SSL 终止的代理服务器的下游)。标准行为由某些请求头(x-forwarded-for
和 x-forwarded-proto
)的存在与否决定,这些请求头的名称是约定俗成的,因此它应该能够与大多数前端代理一起工作。你可以通过在 application.properties
中添加一些条目来启用该阀门,如下例所示:
- Properties
- YAML
server.tomcat.remoteip.remote-ip-header=x-forwarded-for
server.tomcat.remoteip.protocol-header=x-forwarded-proto
server:
tomcat:
remoteip:
remote-ip-header: "x-forwarded-for"
protocol-header: "x-forwarded-proto"
(存在其中任何一个属性都会打开阀门。或者,你可以通过使用 WebServerFactoryCustomizer bean 自定义 TomcatServletWebServerFactory 来添加 RemoteIpValve。)
要配置 Spring Security 以要求所有(或部分)请求使用安全通道,可以考虑添加你自己的 SecurityFilterChain Bean,并添加以下 HttpSecurity 配置:
- Java
- Kotlin
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class MySecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// Customize the application security ...
http.requiresChannel((channel) -> channel.anyRequest().requiresSecure());
return http.build();
}
}
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.web.SecurityFilterChain
@Configuration
class MySecurityConfig {
@Bean
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
// Customize the application security ...
http.requiresChannel { requests -> requests.anyRequest().requiresSecure() }
return http.build()
}
}