You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security 5.7.6日志自动脱敏误触发,如何禁用或调整?

解决Spring Security 5.7.x日志误脱敏问题

问题背景

将Spring Security从5.3.4升级至5.7.6后,日志中包含"key"、"token"、"secret"的内容会被自动脱敏,导致调试所需的正常数据(如URL参数中的primaryKey)被误截断,影响问题排查。

原因分析

该脱敏功能是Spring Security 5.6+版本新增的安全特性,由DefaultMessageSanitizer类实现,默认会匹配上述关键词并对后续内容进行脱敏替换,目的是防止密钥、令牌等敏感信息泄露,但存在误判情况。

解决方案

方法1:完全禁用日志脱敏

通过配置类替换默认的日志 sanitizer 为不做任何处理的空实现:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.web.util.matcher.MessageSanitizer;

@Configuration
public class SecurityLogConfig {

    @Bean
    public SpringSecurityMessageSource springSecurityMessageSource() {
        SpringSecurityMessageSource messageSource = new SpringSecurityMessageSource();
        // 使用NO_OP空实现,不对日志做任何脱敏处理
        messageSource.setMessageSanitizer(MessageSanitizer.NO_OP);
        return messageSource;
    }
}

方法2:自定义脱敏规则

如果不想完全禁用脱敏,只想调整敏感关键词列表(比如移除"key",保留对"token"和"secret"的脱敏),可以自定义DefaultMessageSanitizer:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.web.util.matcher.DefaultMessageSanitizer;
import org.springframework.security.web.util.matcher.MessageSanitizer;

import java.util.Set;

@Configuration
public class SecurityLogConfig {

    @Bean
    public SpringSecurityMessageSource springSecurityMessageSource() {
        SpringSecurityMessageSource messageSource = new SpringSecurityMessageSource();
        // 自定义需要脱敏的关键词集合,按需调整
        Set<String> sensitiveKeywords = Set.of("token", "secret");
        MessageSanitizer sanitizer = new DefaultMessageSanitizer(sensitiveKeywords);
        messageSource.setMessageSanitizer(sanitizer);
        return messageSource;
    }
}

验证

配置完成后重启应用,日志中类似Logging Request: GET mysite.com/fetchData?primaryKey=col1&value=77的内容会原样输出,不会再被误脱敏。

内容的提问来源于stack exchange,提问作者Ruth Bearden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 14:56:06