java—有没有一种方法可以扩展SpringActuator记录器并从我自己的控制器调用它?

qcbq4gxm  于 2021-06-29  发布在  Java
关注(0)|答案(3)|浏览(327)

有没有办法扩展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;
    }

}
gcuhipw9

gcuhipw91#

您可以使用Spring Security 保护端点。请参阅保护http端点。
如果springsecurity不是一个选项,并且您确实希望以其他方式控制日志记录,那么执行器没有提供,您可以查看 LoggersEndpoint :
控制它使用的日志记录级别 LoggingSystem / LoggerGroups 以下是更改日志记录级别的代码片段:

@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);
}
gg0vcinb

gg0vcinb2#

最好的方法是利用spring安全语义。
创建一个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;
    }
}

将bean注入websecurityconfigureradapter并使用 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, no-store, max-age=0, 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

zzlelutf

zzlelutf3#

我同意@denis zavedeev的观点,保护内部端点的最好方法是在security configurer内部,当然如果有可能的话。例如:

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

你的主要目标是阶级 LoggersEndpoint ,正如@denis zavedeev提到的,有一种设置日志级别的方法

@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);
}

当然你可以自动连线 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"));
        }

    }

}

相关问题