Skip to content

doc(Log): add filter for Antiforgery#7830

Merged
ArgoZhang merged 2 commits intomainfrom
doc-filter
Apr 2, 2026
Merged

doc(Log): add filter for Antiforgery#7830
ArgoZhang merged 2 commits intomainfrom
doc-filter

Conversation

@ArgoZhang
Copy link
Copy Markdown
Member

@ArgoZhang ArgoZhang commented Apr 2, 2026

Link issues

fixes #7829

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Adjust logging and data protection configuration for the BootstrapBlazor server application.

Enhancements:

  • Filter out known Antiforgery-related noise from file-based error logging.
  • Simplify data protection configuration by relying on default application name and key storage instead of custom filesystem persistence.

Copilot AI review requested due to automatic review settings April 2, 2026 03:15
@bb-auto bb-auto bot added the documentation Improvements or additions to documentation label Apr 2, 2026
@bb-auto bb-auto bot added this to the v10.5.0 milestone Apr 2, 2026
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai bot commented Apr 2, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Updates server-side service configuration to filter out noisy Antiforgery logs from the file logger and simplifies data protection configuration by removing explicit key persistence and application name settings.

Sequence diagram for filtered Antiforgery logging

sequenceDiagram
    participant RequestPipeline
    participant Antiforgery
    participant LoggerFactory
    participant LoggingBuilder
    participant FileLogger

    RequestPipeline->>Antiforgery: ValidateRequestAsync
    Antiforgery->>LoggerFactory: CreateLogger(Microsoft.AspNetCore.Antiforgery)
    LoggerFactory->>LoggingBuilder: ApplyFilters
    LoggingBuilder->>FileLogger: AddFileLogger
    LoggingBuilder->>FileLogger: AddFilter(Microsoft.AspNetCore.Antiforgery, LogLevel.None)

    Antiforgery->>FileLogger: Log(LogLevel.Warning, category Antiforgery)
    FileLogger-->>Antiforgery: Discard log (filtered out)

    RequestPipeline->>LoggerFactory: CreateLogger(OtherCategory)
    LoggerFactory->>FileLogger: Log(LogLevel.Error, category OtherCategory)
    FileLogger-->>RequestPipeline: Write entry to log file
Loading

File-Level Changes

Change Details Files
Adjust logging setup to filter out Antiforgery noise while continuing to log errors to the file logger.
  • Wrap logging configuration in a lambda block for extensibility
  • Keep file logger registration via AddFileLogger
  • Add a logging filter for the "Microsoft.AspNetCore.Antiforgery" category with LogLevel.None to suppress these entries
src/BootstrapBlazor.Server/Extensions/ServiceCollectionExtensions.cs
Simplify data protection configuration by relying on default settings instead of custom key storage.
  • Remove unused Microsoft.AspNetCore.DataProtection using directive
  • Replace custom DataProtection configuration (application name and file system key persistence) with a simple AddDataProtection() call
src/BootstrapBlazor.Server/Extensions/ServiceCollectionSharedExtensions.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#7829 Add a logging filter to suppress or handle logs from the Antiforgery component in the server's logging configuration.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@ArgoZhang ArgoZhang merged commit 8263d70 into main Apr 2, 2026
5 checks passed
@ArgoZhang ArgoZhang deleted the doc-filter branch April 2, 2026 03:15
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues, and left some high level feedback:

  • The logging filter currently suppresses all logs from Microsoft.AspNetCore.Antiforgery; consider narrowing this to specific log levels or event IDs so you don’t lose potentially useful antiforgery diagnostics.
  • Switching from a configured DataProtection key store to the default AddDataProtection() behavior changes how keys are persisted; verify that the new behavior (e.g., key lifetime and storage location) still fits your requirements for auth cookies and other protected data across app restarts.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The logging filter currently suppresses all logs from `Microsoft.AspNetCore.Antiforgery`; consider narrowing this to specific log levels or event IDs so you don’t lose potentially useful antiforgery diagnostics.
- Switching from a configured `DataProtection` key store to the default `AddDataProtection()` behavior changes how keys are persisted; verify that the new behavior (e.g., key lifetime and storage location) still fits your requirements for auth cookies and other protected data across app restarts.

## Individual Comments

### Comment 1
<location path="src/BootstrapBlazor.Server/Extensions/ServiceCollectionExtensions.cs" line_range="22-25" />
<code_context>
-        // 增加错误日志
-        services.AddLogging(logging => logging.AddFileLogger());
+        // 增加错误日志,并过滤已知的防伪 Token 解密噪音日志
+        services.AddLogging(logging =>
+        {
+            logging.AddFileLogger();
+            logging.AddFilter("Microsoft.AspNetCore.Antiforgery", LogLevel.None);
+        });

</code_context>
<issue_to_address>
**issue (bug_risk):** Consider narrowing the antiforgery logging filter instead of disabling the category entirely.

Setting `Microsoft.AspNetCore.Antiforgery` to `LogLevel.None` suppresses all current and future antiforgery warnings/errors, which may hinder diagnosing production issues. Prefer raising the level (e.g., to `Warning`/`Error`) or filtering only the specific noisy event IDs/messages so critical antiforgery failures remain visible in logs.
</issue_to_address>

### Comment 2
<location path="src/BootstrapBlazor.Server/Extensions/ServiceCollectionSharedExtensions.cs" line_range="101" />
<code_context>
-        services.AddDataProtection()
-            .SetApplicationName("BootstrapBlazor")
-            .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(AppContext.BaseDirectory, "keys")));
+        services.AddDataProtection();

         // 增加 PetaPoco ORM 数据服务操作类
</code_context>
<issue_to_address>
**issue (bug_risk):** Reconsider removing explicit DataProtection app name and key persistence configuration.

Removing `.SetApplicationName("BootstrapBlazor")` and `.PersistKeysToFileSystem(...)` means DataProtection will use host defaults for app isolation and key storage. This can result in ephemeral keys (invalidating auth/antiforgery cookies on restart) or unintended key sharing between apps, especially in scaled or long‑running deployments. If this configuration isn’t being set elsewhere, it’s safer to keep an explicit application name and persistent key store.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +22 to +25
services.AddLogging(logging =>
{
logging.AddFileLogger();
logging.AddFilter("Microsoft.AspNetCore.Antiforgery", LogLevel.None);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Consider narrowing the antiforgery logging filter instead of disabling the category entirely.

Setting Microsoft.AspNetCore.Antiforgery to LogLevel.None suppresses all current and future antiforgery warnings/errors, which may hinder diagnosing production issues. Prefer raising the level (e.g., to Warning/Error) or filtering only the specific noisy event IDs/messages so critical antiforgery failures remain visible in logs.

services.AddDataProtection()
.SetApplicationName("BootstrapBlazor")
.PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(AppContext.BaseDirectory, "keys")));
services.AddDataProtection();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Reconsider removing explicit DataProtection app name and key persistence configuration.

Removing .SetApplicationName("BootstrapBlazor") and .PersistKeysToFileSystem(...) means DataProtection will use host defaults for app isolation and key storage. This can result in ephemeral keys (invalidating auth/antiforgery cookies on restart) or unintended key sharing between apps, especially in scaled or long‑running deployments. If this configuration isn’t being set elsewhere, it’s safer to keep an explicit application name and persistent key store.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR targets reducing log noise in the BootstrapBlazor.Server sample by filtering Antiforgery-related logs during service registration.

Changes:

  • Added a logging filter to suppress Microsoft.AspNetCore.Antiforgery logs.
  • Simplified Data Protection registration by removing explicit application name and key persistence configuration.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
src/BootstrapBlazor.Server/Extensions/ServiceCollectionSharedExtensions.cs Removes explicit Data Protection key ring persistence/application name configuration and leaves default AddDataProtection() behavior.
src/BootstrapBlazor.Server/Extensions/ServiceCollectionExtensions.cs Adds Antiforgery log filtering alongside existing file logger setup.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 99 to +101

// 增加密钥存储配置
services.AddDataProtection()
.SetApplicationName("BootstrapBlazor")
.PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(AppContext.BaseDirectory, "keys")));
services.AddDataProtection();
Copy link

Copilot AI Apr 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

services.AddDataProtection() used to set SetApplicationName("BootstrapBlazor") and persist the key ring to a known path. This PR removes that configuration entirely, which can change where keys are stored and how antiforgery/data-protection payloads are decrypted across restarts/instances. If the intent is only to reduce Antiforgery log noise (per PR title/issue), consider reverting this change or explicitly documenting/configuring the new key storage strategy (e.g., still set an application name and persist keys to a stable, writable location).

Copilot uses AI. Check for mistakes.
@@ -99,9 +98,7 @@ public static IServiceCollection AddBootstrapBlazorServices(this IServiceCollect
services.AddBootstrapBlazorRegionService();

// 增加密钥存储配置
Copy link

Copilot AI Apr 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment says "增加密钥存储配置" (add key storage configuration), but the code now only calls AddDataProtection() without configuring key persistence/application name. Either update the comment to reflect the new behavior or keep an explicit key storage configuration so the comment and behavior stay aligned.

Suggested change
// 增加密钥存储配置
// 增加数据保护服务

Copilot uses AI. Check for mistakes.
services.AddLogging(logging =>
{
logging.AddFileLogger();
logging.AddFilter("Microsoft.AspNetCore.Antiforgery", LogLevel.None);
Copy link

Copilot AI Apr 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AddFilter("Microsoft.AspNetCore.Antiforgery", LogLevel.None) suppresses all antiforgery logs. That can hide potentially important warnings (e.g., repeated invalid token submissions) in addition to the known decryption noise. Consider filtering to a higher minimum level (e.g., LogLevel.Error) or filtering only the specific event/message you want to suppress, so security-relevant antiforgery signals are still available.

Suggested change
logging.AddFilter("Microsoft.AspNetCore.Antiforgery", LogLevel.None);
logging.AddFilter("Microsoft.AspNetCore.Antiforgery", LogLevel.Error);

Copilot uses AI. Check for mistakes.
@codecov
Copy link
Copy Markdown

codecov bot commented Apr 2, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (d49b19e) to head (e1a85f6).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #7830   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          764       764           
  Lines        34142     34142           
  Branches      4701      4701           
=========================================
  Hits         34142     34142           
Flag Coverage Δ
BB 100.00% <ø> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

doc(Log): add filter for Antiforgery

2 participants