| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.AspNetCore.Routing;
- using System;
- using System.Linq;
- namespace EasyTemplate.Tool.Util
- {
- /// <summary>
- /// 在每次请求到达 EndpointMiddleware 之前,移除 Endpoint 的 antiforgery 相关 metadata,
- /// 从而避免框架检查到 antiforgery metadata 时要求 app.UseAntiforgery()。
- /// 注意:此方式会全局禁用基于 Endpoint metadata 的 antiforgery 要求,请确保 API 使用其他鉴权(如 JWT)。
- /// </summary>
- public static class AntiforgeryExtensions
- {
- public static IApplicationBuilder UseRemoveAntiforgeryMetadataGlobally(this IApplicationBuilder app)
- {
- return app.Use(async (context, next) =>
- {
- var endpoint = context.GetEndpoint();
- if (endpoint != null)
- {
- var original = endpoint.Metadata.ToArray();
- // 明确要移除的 antiforgery 相关类型
- var antiforgeryTypes = new Type[]
- {
- typeof(AutoValidateAntiforgeryTokenAttribute),
- typeof(ValidateAntiForgeryTokenAttribute),
- typeof(IgnoreAntiforgeryTokenAttribute)
- };
- var filtered = original.Where(m => !antiforgeryTypes.Any(t => t.IsInstanceOfType(m))).ToArray();
- var needReplace = original.Length != filtered.Length || !original.SequenceEqual(filtered);
- if (needReplace)
- {
- var newEndpoint = new Endpoint(endpoint.RequestDelegate, new EndpointMetadataCollection(filtered), endpoint.DisplayName);
- // 将新的 endpoint 设置到当前请求上下文,后续 EndpointMiddleware 会使用它
- context.SetEndpoint(newEndpoint);
- }
- }
- await next();
- });
- }
- // 保留一个兼容的短路方法(如果需要)
- public static IApplicationBuilder UseAntiforgeryValidation(this IApplicationBuilder app)
- {
- return app.Use(async (context, next) =>
- {
- var endpoint = context.GetEndpoint();
- if (endpoint?.Metadata?.GetMetadata<IgnoreAntiforgeryTokenAttribute>() != null)
- {
- await next();
- return;
- }
- var path = context.Request.Path.Value ?? string.Empty;
- if (path.StartsWith("/api/", StringComparison.OrdinalIgnoreCase))
- {
- await next();
- return;
- }
- await next();
- });
- }
- }
- }
|