安全
本节讨论有关使用Spring Boot时的安全性问题,包括使用Spring Security和Spring Boot引起的问题。
有关Spring Security的更多信息,请参阅Spring Security项目页面。
关闭Spring Boot安全配置
不管你在应用的什么地方定义了一个使用@EnableWebSecurity注解的@Configuration,它都会关闭Spring Boot中的默认webapp安全设置。想要调整默认值,你可以尝试设置security.*属性(具体查看SecurityProperties和常见应用属性的SECURITY章节)。
改变AuthenticationManager并添加用户账号
如果你提供了一个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
}
如果把它放到一个内部类或一个单独的类中,你将得到最好的结果(也就是不跟很多其他@Beans混合在一起将允许你改变实例化的顺序)。secure web sample是一个有用的参考模板。
如果你遇到了实例化问题(比如,使用JDBC或JPA进行用户详细信息的存储),那将AuthenticationManagerBuilder回调提取到一个GlobalAuthenticationConfigurerAdapter(放到init()方法内以防其他地方也需要authentication manager)可能是个不错的选择,比如:
@Configuration
public class AuthenticationManagerConfiguration extends
GlobalAuthenticationConfigurerAdapter {
@Override
public void init(AuthenticationManagerBuilder auth) {
auth.inMemoryAuthentication() // ... etc.
}
}
当前端使用代理服务器时启用HTTPS
对于任何应用来说,确保所有的主端点(URL)都只在HTTPS下可用是个重要的苦差事。如果你使用Tomcat作为servlet容器,那Spring Boot如果发现一些环境设置的话,它将自动添加Tomcat自己的RemoteIpValve,你也可以依赖于HttpServletRequest来报告是否请求是安全的(即使代理服务器的downstream处理真实的SSL终端)。这个标准行为取决于某些请求头是否出现(x-forwarded-for和x-forwarded-proto),这些请求头的名称都是约定好的,所以对于大多数前端和代理都是有效的。
你可以向application.properties添加以下设置开启该功能,比如:
server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto