本节将解决使用 Spring Boot 时有关安全性的问题,包括将 Spring Security 与 Spring Boot 一起使用时出现的问题。Spring中文文档

有关 Spring Security 的更多信息,请参阅 Spring Security 项目页面Spring中文文档

关闭 Spring Boot 安全配置

如果在应用程序中定义 bean with bean,则此操作将关闭 Spring Boot 中的默认 webapp 安全设置。@ConfigurationSecurityFilterChainSpring中文文档

更改 UserDetailsService 并添加用户帐户

如果提供 、 或 类型的 ,则不会创建默认值。 这意味着您拥有 Spring Security 的全部功能集(例如各种身份验证选项)。@BeanAuthenticationManagerAuthenticationProviderUserDetailsService@BeanInMemoryUserDetailsManagerSpring中文文档

添加用户帐户的最简单方法是提供您自己的 Bean。UserDetailsServiceSpring中文文档

在代理服务器后面运行时启用 HTTPS

确保所有主端点仅通过 HTTPS 可用对于任何应用程序来说都是一项重要的苦差事。 如果将 Tomcat 用作 servlet 容器,则 Spring Boot 会在检测到某些环境设置时自动添加 Tomcat 自己的容器,从而允许您依赖 to 报告它是否安全(甚至在处理实际 SSL 终止的代理服务器的下游)。 标准行为由某些请求标头 ( 和 ) 的存在与否决定,这些标头的名称是约定的,因此它应该适用于大多数前端代理。 您可以通过向 添加一些条目来打开阀门,如以下示例所示:RemoteIpValveHttpServletRequestx-forwarded-forx-forwarded-protoapplication.propertiesSpring中文文档

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"

(这些属性中的任何一个的存在都会打开阀门。 或者,您可以通过自定义 using a bean 来添加 。RemoteIpValveTomcatServletWebServerFactoryWebServerFactoryCustomizerSpring中文文档

要将 Spring Security 配置为需要所有(或某些)请求的安全通道,请考虑添加您自己的 bean 以添加以下配置:SecurityFilterChainHttpSecuritySpring中文文档

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()
	}

}