我在想,我是否应该审计热巧克力v11的HttpRequestInterceptor或DiagnosticEventListener中的用户查询。后者的问题是,如果审计未能写入disk/db,用户将“逃脱”查询。
理想情况下,如果审计失败,则不应进行任何操作。因此,理论上我应该使用HttpRequestInterceptor。
但是如何从IRequestExecutor或IQueryRequestBuilder获取IRequestContext呢?我试着用谷歌搜索,但文档有限。
发布于 2021-05-07 17:54:46
都不是:)
HttpRequestInterceptor用于用上下文数据丰富GraphQL请求。
另一方面,DiagnosticEventListener用于日志记录或其他检测。
如果你想写一个审计日志,你应该选择一个请求中间件。可以添加一个请求中间件,如下所示。
services
.AddGraphQLServer()
.AddQueryType<Query>()
.UseRequest(next => async context =>
{
})
.UseDefaultPipeline();这里的棘手部分是在正确的时间检查请求。您可以定义自己的管道,而不是附加到默认管道,如下所示。
services
.AddGraphQLServer()
.AddQueryType<Query>()
.UseInstrumentations()
.UseExceptions()
.UseTimeout()
.UseDocumentCache()
.UseDocumentParser()
.UseDocumentValidation()
.UseRequest(next => async context =>
{
// write your audit log here and invoke next if the user is allowed to execute
if(isNotAllowed)
{
// if the user is not allowed to proceed create an error result.
context.Result = QueryResultBuilder.CreateError(
ErrorBuilder.New()
.SetMessage("Something is broken")
.SetCode("Some Error Code")
.Build())
}
else
{
await next(context);
}
})
.UseOperationCache()
.UseOperationResolver()
.UseOperationVariableCoercion()
.UseOperationExecution();管道基本上是默认管道,但会在文档验证之后立即添加您的中间件。此时,您的GraphQL请求已被解析和验证。这意味着我们知道这是一个可以在此时处理的有效GraphQL请求。这也意味着我们可以使用包含已解析的GraphQL请求的context.Document属性。
要将文档序列化为格式化字符串,请使用context.Document.ToString(indented: true)。
好消息是,在中间件中,我们处于异步上下文中,这意味着您可以轻松地访问数据库等。与此形成对比是,DiagnosticEvents是同步的,并不意味着具有繁重的工作负载。
中间件也可以包装到类中,而不是委托中。
如果您需要更多帮助,请加入我们的行列。
点击社区支持加入松弛频道:https://github.com/ChilliCream/hotchocolate/issues/new/choose
https://stackoverflow.com/questions/67431306
复制相似问题