首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有没有一种方法可以扩展Spring记录器并从我自己的控制器调用它?

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

Stack Overflow用户
提问于 2021-01-02 19:20:48
回答 4查看 857关注 0票数 1

有什么方法可以扩展Spring记录器并从我自己的控制器调用它,这样我就可以执行一些安全验证了吗?例如,如下所示:

代码语言:javascript
运行
复制
@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;
    }

}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2021-01-02 20:16:02

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

如果Security不是一个选项,而且您的do希望以其他方式控制日志记录,执行器不提供这种方式,那么您可以查看LoggersEndpoint

  • 为了控制日志记录级别,它使用LoggingSystem / LoggerGroups
  • 下面是更改日志记录级别的代码片段:@WriteOperation void configureLogLevel(@Selector String name,@Nullable LogLevel configuredLevel) { Assert.notNull(name,"Name不能为空“);LoggerGroup group = this.loggerGroups.get(name);if (group != null & group.hasMembers()) { group.configureLogLevel(configuredLevel,this.loggingSystem::setLogLevel);返回;}this.loggingSystem.setLogLevel(名称,configuredLevel);
票数 2
EN

Stack Overflow用户

发布于 2021-01-02 20:50:25

最好是利用Spring安全语义。

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

代码语言:javascript
运行
复制
@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方法:

代码语言:javascript
运行
复制
    @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)");
        });
    }

就是这样。

代码语言:javascript
运行
复制
$ http -a user:password localhost:8080/actuator/loggers
// 403


$ http -a admin:password localhost:8080/actuator/loggers
// 200
代码语言:javascript
运行
复制
$ 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
代码语言:javascript
运行
复制
$ 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

票数 3
EN

Stack Overflow用户

发布于 2021-01-02 20:42:05

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

代码语言:javascript
运行
复制
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().ignoringAntMatchers("/actuator/**");
}

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

代码语言:javascript
运行
复制
@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);
}

当然,如果我们看一看自动配置,您可以自动访问bean LoggersEndpoint并调用适当的写方法:

代码语言:javascript
运行
复制
@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"));
        }

    }

}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65543132

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档