有没有办法扩展 Spring Actuator 记录器并从我自己的控制器调用它?

问题描述

有没有办法扩展 Spring Actuator 记录器并从我自己的控制器调用它,以便我可以进行一些安全验证?例如,像这样:

@RestController
public class MyLoggingController {

    @Autowired
    private ActuatorLogger logger; // not sure what the actual class name is

    @PostMapping("/loggers")
    public String setLoggeringLevel( @RequestBody String body ) {
        
        // do security validations 
        
        // set logging level
        logger.setLoggingLevel( ... ); // not sure what the actual method signature is
        
        return response;
    }

}

解决方法

最好是利用 Spring Security 语义。

创建一个 bean,该 bean 将具有用于检查特定身份验证主体的访问的单一方法:

@Component
public class SetLoggerAccessChecker {

    public boolean isAuthorizedToChangeLogs(Authentication authentication,HttpServletRequest request) {
        // example custom logic below,implement your own
        if (request.getMethod().equals(HttpMethod.POST.name())) {
            return ((User) authentication.getPrincipal()).getUsername().equals("admin");
        }

        return true;
    }
}

在 WebSecurityConfigurerAdapter 中注入 bean 并对特定的 ActuatorLoggerEndpoints 使用 access 方法:

    @Autowired
    private SetLoggerAccessChecker setLoggerAccessChecker;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").httpBasic();
        http.csrf().disable().requestMatcher(EndpointRequest.to(LoggersEndpoint.class)).authorizeRequests((requests) -> {
            requests.anyRequest().access("@setLoggerAccessChecker.isAuthorizedToChangeLogs(authentication,request)");
        });
    }

就是这样。

$ http -a user:password localhost:8080/actuator/loggers
// 403


$ http -a admin:password localhost:8080/actuator/loggers
// 200
$ curl --user "admin:password" -i -X POST -H 'Content-Type: application/json' -d '{"configuredLevel": "DEBUG"}' http://localhost:8080/actuator/loggers/com.ikwattro
HTTP/1.1 204
Set-Cookie: JSESSIONID=A013429ADE8B58239EBE385B9DEC524D; Path=/; HttpOnly
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache,no-store,max-age=0,must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Date: Sat,02 Jan 2021 22:38:26 GMT
$ curl --user "user:password" -i -X POST -H 'Content-Type: application/json' -d '{"configuredLevel": "DEBUG"}' http://localhost:8080/actuator/loggers/com.ikwattro
HTTP/1.1 403
Set-Cookie: JSESSIONID=2A350627672B6742F5C842D2A3BC1330; Path=/; HttpOnly
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache,must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Disposition: inline;filename=f.txt
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sat,02 Jan 2021 22:41:04 GMT

此处的示例存储库:https://github.com/ikwattro/spring-boot-actuator-custom-security

,

您可以使用 Spring Security 保护端点。见Securing HTTP Endpoints


如果 Spring Security 不是一个选项,并且您确实想以其他方式控制日志记录,该执行器不提供,您可以查看{{ 3}}:

  • 为了控制日志级别,它使用 LoggersEndpoint / LoggingSystem
  • 以下是更改日志记录级别的代码片段:
    @WriteOperation
    public void configureLogLevel(@Selector String name,@Nullable LogLevel configuredLevel) {
        Assert.notNull(name,"Name must not be empty");
        LoggerGroup group = this.loggerGroups.get(name);
        if (group != null && group.hasMembers()) {
            group.configureLogLevel(configuredLevel,this.loggingSystem::setLogLevel);
            return;
        }
        this.loggingSystem.setLogLevel(name,configuredLevel);
    }
    
,

我同意@Denis Zavedeev,保护内部端点的最佳方法是在安全配置器内部,当然,如果有可能的话。 例如:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().ignoringAntMatchers("/actuator/**");
}

您的主要目标是类 LoggersEndpoint,正如@Denis Zavedeev 提到的,有设置日志级别的方法

@WriteOperation
public void configureLogLevel(@Selector String name,configuredLevel);
}

当然你可以自动装配 bean LoggersEndpoint 并调用适当的写入方法,如果我们看一下自动配置:

@Configuration(proxyBeanMethods = false)
@ConditionalOnAvailableEndpoint(endpoint = LoggersEndpoint.class)
public class LoggersEndpointAutoConfiguration {

    @Bean
    @ConditionalOnBean(LoggingSystem.class)
    @Conditional(OnEnabledLoggingSystemCondition.class)
    @ConditionalOnMissingBean
    public LoggersEndpoint loggersEndpoint(LoggingSystem loggingSystem,ObjectProvider<LoggerGroups> springBootLoggerGroups) {
        return new LoggersEndpoint(loggingSystem,springBootLoggerGroups.getIfAvailable(LoggerGroups::new));
    }

    static class OnEnabledLoggingSystemCondition extends SpringBootCondition {

        @Override
        public ConditionOutcome getMatchOutcome(ConditionContext context,AnnotatedTypeMetadata metadata) {
            ConditionMessage.Builder message = ConditionMessage.forCondition("Logging System");
            String loggingSystem = System.getProperty(LoggingSystem.SYSTEM_PROPERTY);
            if (LoggingSystem.NONE.equals(loggingSystem)) {
                return ConditionOutcome.noMatch(
                        message.because("system property " + LoggingSystem.SYSTEM_PROPERTY + " is set to none"));
            }
            return ConditionOutcome.match(message.because("enabled"));
        }

    }

}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...