82. Security

82.1 关闭 Spring Boot 安全性配置

如果在应用程序中的任何位置定义@Configuration@EnableWebSecurity,它将关闭 Spring Boot 中的默认 Webapp 安全设置(但保持启用的 Actuator 的安全性)。要调整默认值,请尝试在security.*中设置设置属性(有关可用设置的详细信息,请参见SecurityProperties)和通用应用程序属性SECURITY部分。

82.2 更改 AuthenticationManager 并添加用户帐户

如果您提供的@Bean的类型为AuthenticationManager,则不会创建默认的@Bean,因此您可以使用完整的 Spring Security 功能集(例如各种身份验证选项)。

Spring Security 还提供了一个方便的AuthenticationManagerBuilder,可以使用通用选项来构建AuthenticationManager。在 webapp 中使用此方法的推荐方法是将其注入到WebSecurityConfigurerAdapter中的 void 方法中,例如

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                .withUser("barry").password("password").roles("USER"); // ... etc.
    }

    // ... other stuff for application security

}

如果将其放在嵌套类或独立类中(即不要与可能允许影响实例化 Sequences 的其他@Beans混合使用),则将获得最佳结果。 安全的网络 samples是一个有用的模板。

如果您遇到实例化问题(例如,将 JDBC 或 JPA 用于用户详细信息存储),则可能值得将AuthenticationManagerBuilder回调提取到GlobalAuthenticationConfigurerAdapter中(在init()方法中,因此发生在需要其他地方的身份验证 Management 器之前),例如

@Configuration
public class AuthenticationManagerConfiguration extends
        GlobalAuthenticationConfigurerAdapter {

    @Override
    public void init(AuthenticationManagerBuilder auth) {
        auth.inMemoryAuthentication() // ... etc.
    }

}

82.3 在代理服务器上运行时启用 HTTPS

确保所有主要端点仅可通过 HTTPS 进行访问对于任何应用程序来说都是一项重要的工作。如果您将 Tomcat 用作 servlet 容器,则 Spring Boot 如果检测到某些环境设置,它将自动添加 Tomcat 自己的RemoteIpValve,并且您应该能够依靠HttpServletRequest报告它是否安全(甚至在代理下游)处理实际 SSL 终止的服务器)。标准行为由某些请求 Headers(x-forwarded-forx-forwarded-proto)的存在或不存在决定,它们的名称是常规名称,因此它应适用于大多数前端代理。您可以通过向application.properties添加一些条目来打开阀门,例如

server.tomcat.remote-ip-header=x-forwarded-for
server.tomcat.protocol-header=x-forwarded-proto

(这些属性中的任何一个都会打开阀门.或者您可以通过添加TomcatEmbeddedServletContainerFactory bean 来自己添加RemoteIpValve.)

Spring Security 也可以配置为要求所有(或某些请求)安全通道。要在 Spring Boot 应用程序中打开它,您只需要在application.properties中将security.require_ssl设置为true即可。

上一章 首页 下一章