Spring Boot 安全性最佳实践

https://www.518cn.com   发布时间:2025-03-18 18:52   作者:网络
摘要:Spring Boot 安全性最佳实践 1.实施 HTTPSHTTPS 在传输过程中对数据进行加密,防止未经授权的各方截获和破译敏感信息。这对于处理用户凭证、金融交易或任何其他机密数据的应用程序尤为

Spring Boot 安全性最佳实践

1.实施 HTTPS

HTTPS 在传输过程中对数据进行加密,防止未经授权的各方截获和破译敏感信息。这对于处理用户凭证、金融交易或任何其他机密数据的应用程序尤为重要。因此,安全通信是不容置疑的。您必须使用 HTTPS 来保护传输中的数据。

在应用程序属性中,确保启用 TLS/SSL:

server.port=8443 server.ssl.key-store=classpath:keystore.jks server.ssl.key-store-password=yourpassword server.ssl.key-password=yourpassword

调整文件路径,确保将 "keystore.jks"、"key-store-password "和 "key-password "替换为实际的 keystore 文件、keystore 密码和私钥密码。

如果想强制执行 HTTPS 并完全禁止 HTTP 访问,可以修改 Spring Security 配置,将所有 HTTP 流量重定向到 HTTPS。下面是实现方法:

@Override protected void configure(HttpSecurity http) throws Exception { http .requiresChannel() .requestMatchers(r -> r.getHeader("X-Forwarded-Proto") != null) .requiresSecure() .and() .authorizeRequests() .antMatchers("/").permitAll() // Allow access to the home page .anyRequest().authenticated() .and() .formLogin().and() .httpBasic().and() .csrf().and(); // Retaining CSRF configuration }

.requiresChannel().requestMatchers(r -> r.getHeader("X-Forwarded-Proto") != null).requiresSecure() 对所有请求强制执行 HTTPS。requestMatchers 部分用于处理应用程序位于代理或负载平衡器后面的情况,X-Forwarded-Proto 用于确定协议。如果要在 Spring Boot 应用程序中使用 WebSecurityConfigurerAdapter 强制执行 HTTPS,可以配置安全设置以确保安全连接。下面是一个完整的示例:
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.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .requiresChannel() .requestMatchers(r -> r.getHeader("X-Forwarded-Proto") != null) .requiresSecure() // Enforce HTTPS .and() .authorizeRequests() .antMatchers("/").permitAll() // Allow access to the home page .anyRequest().authenticated() .and() .formLogin().and() .httpBasic().and() .csrf().and(); // Retain CSRF protection } }

实施 HTTPS 后,彻底测试应用程序,确保功能无缝连接。定期监控 SSL/TLS 配置,检查是否存在漏洞或证书过期。
2.激活 CSRF 保护 
跨站请求伪造(CSRF)攻击可能是毁灭性的。Spring Security 默认启用 CSRF 保护。请确保没有误将其禁用:
http .csrf().disable(); // Avoid this in production
3.严格验证输入 
绝不相信用户输入。始终验证类型、长度、格式和范围。使用 Spring 内置的验证功能:
import javax.validation.constraints.NotEmpty; public class UserInput { @NotEmpty(message = "Name cannot be empty") private String name; // getters and setters }

4.使用参数化查询

SQL 注入是网络应用程序中常见的非常关键的漏洞,攻击者可以完全接管应用程序的数据库。

在 Spring Boot 中,可以通过使用参数化查询或 JPA 资源库来缓解 SQL 注入攻击:

@Repository public interface UserRepository extends JpaRepository<User, Long> { @Query("SELECT u FROM User u WHERE u.email = :email") User findByEmail(@Param("email") String email); }

5.启用方法级安全

当未经授权或低权限用户可以访问应用程序的敏感功能(如通常由管理员角色访问的功能)时,就会出现方法级授权问题。

这一问题在网络应用程序中非常普遍,已成为 OWASP 评选的网络应用程序十大漏洞之一。

您可以使用 Spring 安全注解在方法级别限制访问权限,从而避免这一安全问题:

@PreAuthorize("hasRole('ADMIN')") public void deleteUser(Long id) { // deletion logic }
6.加密敏感数据 
想要避免数据泄露?敏感数据应该加密。使用 Spring 的 @EncryptablePropertySource 对属性文件进行加密:
@EncryptablePropertySource(name = "EncryptedProperties", value = "classpath:encrypted.properties") @Configuration public class EncryptionConfig { // Configuration details }

7.定期更新依赖项

Spring Boot 漏洞经常出现在第三方软件包和插件中。及时更新依赖项,下载开发人员创建的补丁,确保已知的安全漏洞得到修复。使用 Maven 或 Gradle 等工具可轻松进行管理。

最近, 等开源依赖关系扫描工具增加了对扫描易受攻击的 Java 依赖关系的支持。

8.实施正确的身份验证和授权

利用 Spring Security 强大的身份验证和授权机制。配置身份验证提供程序、userDetailsService 和密码编码器:

@Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder()); }
9.审计和记录安全事件 
安全审计对于正确评估组织应用程序的安全状况至关重要。我们强烈建议跟踪所有与安全相关的事件。Spring Boot Actuator 和 Spring Security 的审计功能非常有用:
public class CustomAuditListener extends AbstractAuthenticationAuditListener { @Override public void onApplicationEvent(AbstractAuthenticationEvent event) { // Logging logic } }

10.进行安全测试

定期测试应用程序是否存在安全漏洞。

您可以使用 Spring Boot 自身的测试功能来编写测试:

@SpringBootTest public class SecurityConfigurationTest { // Test cases }

但这种方法可能会很耗时,尤其是因为您需要为多种类型的安全漏洞创建和维护所有测试用例。更快、更可靠的替代方法是使用支持 Spring Boot 的专用 API 测试工具(如 Escape),它将直接在 CI/CD 中根据 100 多种安全最佳实践和漏洞测试您的应用程序,并帮助您修复所有问题。

结论

      这篇文章基于Spring Security, Spring Boot 中的安全性不是事后的想法,而是应用程序设计的一个重要方面。通过遵循这些最佳实践,开发人员可以显著改善 Spring Boot 应用程序的安全状况。请记住,全面的安全性不仅需要最佳实践,还需要实施强大的访问控制措施、执行安全的编码实践以及采用最新的安全技术,从而大幅降低风险敞口,保护您的宝贵资产免受潜在威胁。


今天先到这儿,希望对云原生,技术领导力, 企业管理,系统架构设计与评估,团队管理, 项目管理, 产品管管,团队建设 有参考作用 , 您可能感兴趣的文章:

































如有想了解更多软件设计与架构, 系统IT,企业信息化, 团队管理 资讯,请关注我的微信订阅号:

作者:
出处:
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 该文章也同时发布在我的独立博客中-Petter Liu Blog。

相关文章

最新评论