本文目录导读:

我来为您设计一个统一的Java监控安全流程方案。
整体架构设计
graph TB
A[业务应用] --> B[安全监控层]
B --> C[数据采集]
C --> D[分析引擎]
D --> E[告警系统]
E --> F[响应处理]
subgraph B[安全监控层]
B1[APM监控]
B2[安全审计]
B3[性能监控]
end
核心实现方案
统一监控框架
// 监控配置管理
@Configuration
@EnableAspectJAutoProxy
public class SecurityMonitorConfig {
@Bean
public MonitorInterceptor monitorInterceptor() {
return new MonitorInterceptor();
}
@Bean
public SecurityAuditor securityAuditor() {
return new SecurityAuditor();
}
}
// 监控注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Monitored {
String businessType() default "";
boolean logParams() default true;
boolean logResult() default false;
SecurityLevel securityLevel() default SecurityLevel.NORMAL;
}
// 安全级别枚举
public enum SecurityLevel {
NORMAL, // 普通
SENSITIVE, // 敏感
CRITICAL // 关键
}
安全监控切面实现
@Component
@Aspect
@Slf4j
public class SecurityMonitorAspect {
@Autowired
private MetricsCollector metricsCollector;
@Autowired
private EventPublisher eventPublisher;
@Around("@annotation(monitored)")
public Object monitorSecurity(ProceedingJoinPoint joinPoint, Monitored monitored) throws Throwable {
String methodName = joinPoint.getSignature().getName();
String businessType = monitored.businessType();
// 创建监控上下文
MonitorContext context = MonitorContext.builder()
.methodName(methodName)
.businessType(businessType)
.securityLevel(monitored.securityLevel())
.startTime(System.currentTimeMillis())
.build();
try {
// 前置安全检测
preSecurityCheck(joinPoint, monitored);
// 执行目标方法
Object result = joinPoint.proceed();
// 后置安全验证
postSecurityCheck(result, monitored);
// 记录成功监控数据
context.setSuccess(true);
context.setResult(result);
return result;
} catch (SecurityException se) {
// 安全异常处理
context.setSuccess(false);
context.setError(se.getMessage());
handleSecurityError(se, context);
throw se;
} catch (Exception e) {
// 业务异常处理
context.setSuccess(false);
context.setError(e.getMessage());
metricsCollector.recordError(context);
throw e;
} finally {
// 完成监控记录
context.setDuration(System.currentTimeMillis() - context.getStartTime());
metricsCollector.record(context);
eventPublisher.publishEvent(new MonitorEvent(context));
}
}
private void preSecurityCheck(ProceedingJoinPoint point, Monitored monitored) {
if (monitored.securityLevel() == SecurityLevel.CRITICAL) {
// 获取当前用户权限
SecurityContext securityContext = SecurityContextHolder.getContext();
// 检查权限
if (!hasPermission(securityContext, monitored.businessType())) {
throw new SecurityException("权限不足");
}
// 检查请求频率
if (isRateLimited(point.getSignature().getName())) {
throw new SecurityException("请求频率超限");
}
// 参数安全校验
Object[] args = point.getArgs();
validateParameters(args);
}
}
private void validateParameters(Object[] args) {
for (Object arg : args) {
if (arg instanceof String) {
// SQL注入检查
if (containsSqlInjection((String) arg)) {
throw new SecurityException("检测到SQL注入风险");
}
// XSS检查
if (containsXss((String) arg)) {
throw new SecurityException("检测到XSS攻击风险");
}
}
}
}
}
数据采集与指标收集
@Component
@Slf4j
public class MetricsCollector {
private final MeterRegistry meterRegistry;
private final Map<String, Counter> securityCounterMap = new ConcurrentHashMap<>();
private final Map<String, Timer> securityTimerMap = new ConcurrentHashMap<>();
public MetricsCollector(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
}
public void record(MonitorContext context) {
// 记录请求计数
Counter counter = securityCounterMap.computeIfAbsent(
context.getBusinessType() + "_" + context.getSecurityLevel(),
key -> Counter.builder("security.request.total")
.tag("business", context.getBusinessType())
.tag("level", context.getSecurityLevel().name())
.register(meterRegistry)
);
counter.increment();
// 记录响应时间
Timer timer = securityTimerMap.computeIfAbsent(
context.getMethodName(),
key -> Timer.builder("security.request.duration")
.tag("method", context.getMethodName())
.register(meterRegistry)
);
timer.record(Duration.ofMillis(context.getDuration()));
// 记录安全事件
if (!context.isSuccess()) {
recordSecurityEvent(context);
}
}
public void recordError(MonitorContext context) {
Counter errorCounter = Counter.builder("security.request.error")
.tag("business", context.getBusinessType())
.tag("error", context.getError())
.register(meterRegistry);
errorCounter.increment();
}
public void recordSecurityEvent(MonitorContext context) {
// 记录安全事件日志
SecurityEvent event = SecurityEvent.builder()
.eventType("SECURITY_VIOLATION")
.severity(context.getSecurityLevel().name())
.source(context.getMethodName())
.details(context.getError())
.timestamp(Instant.now())
.build();
log.warn("Security event: {}", event);
// 发送到事件处理系统
sendToEventSystem(event);
}
}
告警系统实现
@Component
@Slf4j
public class AlertSystem {
@Autowired
private AlertRuleEngine ruleEngine;
@Autowired
private NotificationService notificationService;
@EventListener
public void handleMonitorEvent(MonitorEvent event) {
MonitorContext context = event.getContext();
// 评估告警规则
List<AlertRule> matchedRules = ruleEngine.evaluate(context);
if (!matchedRules.isEmpty()) {
// 生成告警
Alert alert = buildAlert(context, matchedRules);
// 执行告警动作
executeAlert(alert);
}
}
private Alert buildAlert(MonitorContext context, List<AlertRule> rules) {
return Alert.builder()
.alertId(UUID.randomUUID().toString())
.severity(determineSeverity(rules))
.title(String.format("安全监控告警 - %s", context.getBusinessType()))
.description(context.getError())
.source(context.getMethodName())
.timestamp(Instant.now())
.rules(rules)
.build();
}
private void executeAlert(Alert alert) {
// 根据严重级别采取不同措施
switch (alert.getSeverity()) {
case HIGH:
// 立即通知相关负责人
notificationService.sendUrgentNotification(alert);
// 自动触发降级
triggerDegradation(alert);
break;
case MEDIUM:
// 发送邮件通知
notificationService.sendEmailAlert(alert);
// 记录到告警数据库
saveAlertToDb(alert);
break;
case LOW:
// 记录日志
log.warn("Low severity alert: {}", alert);
break;
}
}
}
安全审计日志
@Component
public class SecurityAuditor {
@Autowired
private AuditLogRepository auditLogRepository;
@Async
public void audit(MonitorContext context) {
// 构建审计日志
AuditLog auditLog = AuditLog.builder()
.timestamp(Instant.now())
.userId(getCurrentUserId())
.action(context.getBusinessType())
.resource(context.getMethodName())
.status(context.isSuccess() ? "SUCCESS" : "FAILURE")
.details(JsonUtils.toJson(context))
.ipAddress(getClientIp())
.userAgent(getUserAgent())
.build();
// 持久化审计日志
auditLogRepository.save(auditLog);
// 敏感操作额外记录到安全日志
if (context.getSecurityLevel() == SecurityLevel.CRITICAL) {
logSecurityEvent(auditLog);
}
}
@EventListener
public void handleAuditEvent(AuditEvent event) {
if (event.getSeverity() == AuditSeverity.CRITICAL) {
// 实时同步到安全运营中心
syncToSOC(event.getAuditLog());
}
}
}
统一监控配置
# application-monitor.yml
monitor:
security:
enabled: true
levels:
normal:
enabled: true
rate-limit: 1000/min
sensitive:
enabled: true
rate-limit: 100/min
require-audit: true
critical:
enabled: true
rate-limit: 10/min
require-authorization: true
require-audit: true
alert:
rules:
- name: "高频异常告警"
condition: "errorRate > 5% in 1min"
severity: HIGH
actions: [NOTIFICATION, DEGRADATION]
- name: "SQL注入检测"
condition: "sqlInjectionAttempt > 0"
severity: CRITICAL
actions: [BLOCK, NOTIFICATION]
audit:
enabled: true
async: true
retention-days: 365
sensitive-fields:
- password
- token
- creditCard
使用示例
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
@Monitored(businessType = "USER_LOGIN", securityLevel = SecurityLevel.SENSITIVE)
public Result<UserVO> login(@RequestBody LoginRequest request) {
return Result.success(userService.login(request));
}
@PostMapping("/transfer")
@Monitored(businessType = "FUND_TRANSFER", securityLevel = SecurityLevel.CRITICAL)
@PreAuthorize("hasRole('ADMIN')")
public Result<TransferVO> transfer(@RequestBody TransferRequest request) {
return Result.success(userService.transfer(request));
}
}
这个统一监控安全流程方案提供了:
- 统一监控:通过注解方式实现业务监控与安全监控的统一
- 安全检测:自动进行SQL注入、XSS等安全检测
- 指标收集:使用Micrometer收集性能指标
- 告警通知:基于规则引擎的智能告警
- 审计日志:完整的安全审计跟踪
- 配置灵活:可通过配置文件灵活调整监控策略
可以根据实际业务需求进一步扩展和定制。