此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Boot 3.4.0! |
安全
本节解决使用 Spring Boot 时的安全性问题,包括将 Spring Security 与 Spring Boot 一起使用时出现的问题。
有关 Spring Security 的更多信息,请参阅 Spring Security 项目页面。
关闭 Spring Boot 安全配置
如果您定义了@Configuration
替换为SecurityFilterChain
bean,此作将关闭 Spring Boot 中的默认 webapp 安全设置。
更改 UserDetailsService 并添加用户帐户
如果您提供@Bean
的类型AuthenticationManager
,AuthenticationProvider
或UserDetailsService
,则默认的@Bean
为InMemoryUserDetailsManager
未创建。
这意味着您拥有可用的 Spring Security 的完整功能集(例如各种身份验证选项)。
添加用户帐户的最简单方法是提供您自己的帐户UserDetailsService
豆。
在代理服务器后运行时启用 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"
(这些属性中的任何一个的存在都会打开阀门。
或者,您也可以添加RemoteIpValve
通过自定义TomcatServletWebServerFactory
使用WebServerFactoryCustomizer
bean。
要将 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()
}
}