C# SOAP API Basic Authentication是否仅支持.NET Core?有无.NET 4.6.2示例?
适用于.NET Framework 4.6.2 SOAP服务的Basic Authentication实现方案
.NET Framework 4.6.2下的SOAP服务(通常为WCF服务或ASMX服务)无需依赖.NET Core的中间件体系,通过自定义HTTP模块即可实现Basic认证,核心逻辑为解析请求头的Authorization字段、校验账号密码有效性,校验失败直接返回401状态码。
实现步骤(WCF/ASMX服务通用)
1. 自定义HTTP认证模块
新建类实现IHttpModule接口,完成认证逻辑:
using System; using System.Net; using System.Web; using System.Text; using System.Security.Principal; public class BasicAuthHttpModule : IHttpModule { public void Init(HttpApplication context) { context.AuthenticateRequest += OnAuthenticateRequest; context.EndRequest += OnEndRequest; } private void OnAuthenticateRequest(object sender, EventArgs e) { var app = (HttpApplication)sender; string authHeader = app.Request.Headers["Authorization"]; // 无符合要求的认证头时返回认证要求 if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Basic ")) { SendAuthChallenge(app); return; } try { // 解析Base64编码的账号密码 string encodedCredentials = authHeader.Substring("Basic ".Length).Trim(); byte[] credentialBytes = Convert.FromBase64String(encodedCredentials); string[] credentials = Encoding.UTF8.GetString(credentialBytes).Split(':'); string username = credentials[0]; string password = credentials[1]; // 替换为实际业务的账号密码校验逻辑,例如查询数据库 if (!ValidateCredentials(username, password)) { SendAuthChallenge(app); return; } // 校验通过后设置身份标识,后续业务逻辑可直接读取 IIdentity identity = new GenericIdentity(username); IPrincipal principal = new GenericPrincipal(identity, null); app.Context.User = principal; } catch { SendAuthChallenge(app); return; } } // 自定义账号密码校验规则 private bool ValidateCredentials(string username, string password) { // 示例逻辑,生产环境请替换为实际校验规则 return username == "api_user" && password == "Api@Pass2024"; } // 返回401认证要求 private void SendAuthChallenge(HttpApplication app) { app.Response.StatusCode = (int)HttpStatusCode.Unauthorized; app.Response.AddHeader("WWW-Authenticate", "Basic realm=\"SOAP API Service\""); app.CompleteRequest(); } private void OnEndRequest(object sender, EventArgs e) { var app = (HttpApplication)sender; if (app.Response.StatusCode == (int)HttpStatusCode.Unauthorized) { app.Response.AddHeader("WWW-Authenticate", "Basic realm=\"SOAP API Service\""); } } public void Dispose() { // 无需要释放的托管资源可留空 } }
2. 注册认证模块
在项目的web.config中添加配置,根据IIS运行模式选择对应配置:
IIS集成模式配置
<system.webServer> <modules runAllManagedModulesForAllRequests="true"> <add name="BasicAuthModule" type="BasicAuthHttpModule" preCondition="managedHandler" /> </modules> <security> <!-- 禁用IIS默认Basic认证,避免和自定义逻辑冲突 --> <authentication> <basicAuthentication enabled="false" /> </authentication> </security> </system.webServer>
IIS经典模式配置
<system.web> <httpModules> <add name="BasicAuthModule" type="BasicAuthHttpModule" /> </httpModules> </system.web>
3. 业务逻辑读取认证身份(可选)
如果服务接口需要获取当前登录的用户名,可直接在服务方法中读取:
// WCF服务中读取 string currentUser = Thread.CurrentPrincipal.Identity.Name; // ASMX服务中读取 string currentUser = HttpContext.Current.User.Identity.Name;
注意事项
- Basic认证的账号密码仅做Base64编码,属于明文传输,生产环境必须配合HTTPS使用,避免凭证泄露
- 如果仅需要对部分SOAP接口做认证,可以在认证逻辑中添加请求路径判断,跳过不需要认证的接口
- 可以在
ValidateCredentials方法中扩展权限校验、访问频次限制等业务逻辑
内容的提问来源于stack exchange,提问作者WeiEr
相关产品推荐
相关产品推荐

