面试题答案
一键面试身份验证
- HTTP Basic认证:
在Spring Boot应用中配置
spring-boot-starter-security
依赖,通过简单配置用户名和密码,为Actuator端点启用HTTP Basic认证。示例配置如下:
spring.security.user.name=admin
spring.security.user.password=password
spring.security.user.roles=ADMIN
- OAuth2认证:
引入
spring-boot-starter-oauth2-resource-server
和spring-boot-starter-oauth2-client
依赖,使用OAuth2协议进行认证。配置资源服务器,验证来自授权服务器的令牌。例如:
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/actuator/**").authenticated()
.anyRequest().permitAll();
}
}
授权机制
- 基于角色的访问控制(RBAC):
结合Spring Security,根据用户角色来控制对Actuator端点的访问。比如,只有具有
ADMIN
角色的用户才能访问敏感的/actuator/env
或/actuator/shutdown
端点。配置如下:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/actuator/health").permitAll()
.antMatchers("/actuator/info").permitAll()
.antMatchers("/actuator/**").hasRole("ADMIN")
.anyRequest().authenticated();
}
}
- 基于资源的访问控制(RBAC): 除了角色,还可以根据具体资源的属性来授权访问。例如,特定的团队成员只能访问与他们团队相关的微服务的Actuator端点。
数据加密
- 传输层加密(TLS/SSL):
为微服务配置SSL证书,使得Actuator端点在传输数据时使用HTTPS协议。在Spring Boot中,可以通过配置
server.ssl
属性来启用SSL。示例:
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=password
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias=tomcat
- 数据存储加密: 如果Actuator端点涉及到敏感数据存储(如日志文件等),可以使用加密库对存储的数据进行加密。例如,使用Jasypt库对配置文件中的敏感信息进行加密存储。
防止恶意攻击
- 防止DoS攻击:
配置Spring Security的
RequestMatcher
来限制对Actuator端点的请求频率。可以使用RateLimiter
来实现,例如使用Guava的RateLimiter
:
@Component
public class ActuatorRateLimiter {
private final RateLimiter rateLimiter = RateLimiter.create(10.0); // 每秒允许10个请求
public boolean isAllowed() {
return rateLimiter.tryAcquire();
}
}
然后在Spring Security配置中使用该限制器。
2. 防止SQL注入和XSS攻击:
对于Actuator端点接收用户输入的场景(如自定义的监控查询等),使用预编译语句(如JDBC的PreparedStatement
)来防止SQL注入,并且对输出进行适当的转义来防止XSS攻击。例如,在使用Thymeleaf模板时,Thymeleaf会自动对输出进行HTML转义,以防止XSS。
3. 隐藏敏感端点:
通过配置,隐藏不希望公开暴露的Actuator端点。在application.properties
中可以设置:
management.endpoints.web.exposure.include=health,info
management.endpoints.web.exposure.exclude=env,beans,configprops
这样可以只暴露健康检查和信息端点,隐藏环境变量、Bean定义等敏感端点。