2.8添加授权凭证
在互联网社会中,网络安全愈发关键,特别是在与第三方接口对接时,通常需先通过鉴权授权才能访问。目前,互联网应用接口常用的授权方式包括 Bearer 身份验证、Basic 身份验证、Digest 摘要身份认证和 OAuth 身份认证。
在互联网社会中,网络安全愈发关键,特别是在与第三方接口对接时,通常需先通过鉴权授权才能访问。目前,互联网应用接口常用的授权方式包括 Bearer 身份验证、Basic 身份验证、Digest 摘要身份认证和 OAuth 身份认证。
以下示例展示了如何为 HTTP 远程请求添加授权:
// 添加 Bearer 身份验证await httpRemoteService.SendAsync(HttpRequestBuilder.Get("http://furion.net") .AddBearerAuthentication("your token"));// 添加 Basic 身份验证await httpRemoteService.SendAsync(HttpRequestBuilder.Get("http://furion.net") .AddBasicAuthentication("username", "password"));// 添加 Digest 摘要身份验证await httpRemoteService.SendAsync(HttpRequestBuilder.Get("http://furion.net") .AddDigestAuthentication("username", "password"));// 添加自定义 Schema 身份验证await httpRemoteService.SendAsync(HttpRequestBuilder.Get("http://furion.net") .AddAuthentication(new AuthenticationHeaderValue("X-Token", "your token")));若授权凭证正确,用户即可成功访问网络资源;否则,服务将返回 401 未授权错误。
除了为单个请求手动添加授权凭证外,您还可以通过创建一个自定义的 AuthorizationDelegatingHandler 类继承自 DelegatingHandler 类,实现全局授权凭证的注册:
public class AuthorizationDelegatingHandler : DelegatingHandler{ protected override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) { // 参考 SendAsync 代码 return base.Send(request, cancellationToken); } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // 添加 Bearer 身份验证 request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "your token"); // 添加 Basic 身份验证 var base64Credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes("username" + ":" + "password")); request.Headers.Authorization = new AuthenticationHeaderValue("Basic", base64Credentials); // 添加 Digest 摘要身份验证 var digestCredentials = DigestCredentials.GetDigestCredentials($"https://furion.net/digest", "admin", "a123456789", HttpMethod.Get); request.Headers.Authorization = new AuthenticationHeaderValue("Digest", digestCredentials); // 添加自定义 Schema 身份验证 request.Headers.Authorization = new AuthenticationHeaderValue("X-Token", "your token"); return base.SendAsync(request, cancellationToken); }}注意: 在实际应用中,您应该根据需求选择一种认证方式,而不是在一个请求中同时使用多种认证头。上述代码中的多种认证方式只是为了展示如何设置不同的认证头。
接下来,在 Startup.cs 或 Program.cs 文件中注册 AuthorizationDelegatingHandler:
// 注册 AuthorizationDelegatingHandler 为服务services.TryAddSingleton<AuthorizationDelegatingHandler>();// 为默认客户端启用services.AddHttpClient(string.Empty) .AddHttpMessageHandler<AuthorizationDelegatingHandler>();// 为特定客户端启用//services.AddHttpClient("weixin")// .AddHttpMessageHandler<AuthorizationDelegatingHandler>()这样,每当发送 HTTP 请求时,都会进入 AuthorizationDelegatingHandler 类的 Send/SendAsync 方法,从而自动为请求添加授权凭证。