如何阻止C#客户端响应Basic Authentication 401认证响应?
解决HttpWebRequest仅允许Windows认证的中间人攻击问题
核心思路
强制限定客户端仅接受Negotiate和NTLM认证方案,拒绝Basic等不安全的认证方式,避免被中间人篡改后泄露凭证。
具体实现方案
1. 自定义认证模块
继承IAuthenticationModule接口,只处理Negotiate/NTLM认证,拒绝其他方案:
using System; using System.Net; public class WindowsOnlyAuthModule : IAuthenticationModule { public string AuthenticationType => "Negotiate,NTLM"; public bool CanPreAuthenticate => false; public Authorization Authenticate(string challenge, WebRequest request, ICredentials credentials) { // 仅处理Negotiate或NTLM类型的认证挑战 if (!challenge.StartsWith("Negotiate", StringComparison.OrdinalIgnoreCase) && !challenge.StartsWith("NTLM", StringComparison.OrdinalIgnoreCase)) { // 返回null终止认证流程,不发送任何凭证 return null; } // 调用系统原生的Windows认证逻辑处理合法挑战 var defaultModule = AuthenticationManager.GetModule("Negotiate") ?? AuthenticationManager.GetModule("NTLM"); return defaultModule?.Authenticate(challenge, request, credentials); } public Authorization PreAuthenticate(WebRequest request, ICredentials credentials) { return null; } }
2. 注册并替换默认认证模块
在应用启动阶段注册自定义模块,同时移除默认的Basic认证模块:
// 移除默认Basic认证模块,从根源禁用Basic认证支持 var basicModule = AuthenticationManager.GetModule("Basic"); if (basicModule != null) { AuthenticationManager.Unregister(basicModule); } // 注册自定义的仅Windows认证模块 AuthenticationManager.Register(new WindowsOnlyAuthModule());
3. 配置HttpWebRequest参数
确保请求仅使用Windows认证,关闭自动 fallback:
var request = (HttpWebRequest)WebRequest.Create("https://your-target-server"); request.Credentials = CredentialCache.DefaultCredentials; request.PreAuthenticate = false; // 强制要求双向认证,进一步防范篡改(需服务器支持) request.AuthenticationLevel = AuthenticationLevel.MutualAuthRequired;
关键说明
- 当中间人篡改返回Basic认证挑战时,自定义模块会直接返回null,HttpWebRequest会终止认证流程,不会发送任何凭证。
- 移除默认Basic模块可以彻底避免客户端响应Basic类型的认证请求。
AuthenticationLevel.MutualAuthRequired会要求服务器提供身份验证,进一步降低被篡改的风险。
内容的提问来源于stack exchange,提问作者MEERLIGHT
相关产品推荐
相关产品推荐

