非对称认证方式 可以用在 asp.net webapi 的安全机制里面

复制代码
 //Client端调用
        static void Main(string[] args)
        {
            string publicKey = "DpLMCOihcYI2i6DaMbso9Dzo1miy70G/3+UibTttjLSiJ3cco";
            publicKey += "Kaen3Fecywdf7DrkcfkG3KjeMbZ6djBihD/4A==";
            string privateKey = "W9cE42m+fmBXXvTpYDa2CXIme7DQmk3FcwX0zqR7fmj";
            privateKey += "D6PHHliwdtRb5cOUaxpPyh+3C6Y5Z34uGb2DWD/Awiw==";
            using (HttpClient client = new HttpClient())
            {            // Step 2-a            
                int counter = 33;
                Uri uri = new Uri("http://localhost:54400/api/employees/12345");
                client.DefaultRequestHeaders.Add("X-PSK", publicKey); client.DefaultRequestHeaders.Add("X-Counter", String.Format("{0}", counter));
                // Step 2-b            
                DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);
                TimeSpan ts = DateTime.UtcNow - epochStart;
                string stamp = Convert.ToUInt64(ts.TotalSeconds).ToString();
                client.DefaultRequestHeaders.Add("X-Stamp", stamp);
                string data = String.Format("{0}{1}{2}{3}{4}", publicKey, counter, stamp, uri.ToString(), "GET");
                // Step 2-c            byte[] signature = Encoding.UTF8.GetBytes(data);            using (HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(privateKey)))            {                    byte[] signatureBytes = hmac.ComputeHash(signature);                    client.DefaultRequestHeaders.Add("X-Signature", Convert.ToBase64String(signatureBytes));            } 
                var httpMessage = client.GetAsync(uri).Result; if (httpMessage.IsSuccessStatusCode) Console.WriteLine(httpMessage.Content.ReadAsStringAsync().Result);
            }
        }


        //Server端认真 
        public class PskHandler : DelegatingHandler
        {
            protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                string privateKey = "W9cE42m+fmBXXvTpYDa2CXIme7DQmk3FcwX0zqR7fmj"; privateKey += "D6PHHliwdtRb5cOUaxpPyh+3C6Y5Z34uGb2DWD/Awiw==";
                var headers = request.Headers;
                if (headers.Contains("X-PSK") && headers.Contains("X-Counter") && headers.Contains("X-Stamp") && headers.Contains("X-Signature"))
                {
                    string publicKey = headers.GetValues("X-PSK").First(); string counter = headers.GetValues("X-Counter").First(); ulong stamp = Convert.ToUInt64(headers.GetValues("X-Stamp").First()); string incomingSignature = headers.GetValues("X-Signature").First();
                    string data = String.Format("{0}{1}{2}{3}{4}", publicKey, counter, stamp, request.RequestUri.ToString(), request.Method.Method);
                    byte[] signature = Encoding.UTF8.GetBytes(data); using (HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(privateKey)))
                    {
                        byte[] signatureBytes = hmac.ComputeHash(signature); if (incomingSignature.Equals(Convert.ToBase64String(signatureBytes), StringComparison.Ordinal))
                        {
                            DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc); TimeSpan ts = DateTime.UtcNow - epochStart;
                            if (Convert.ToUInt64(ts.TotalSeconds) - stamp <= 3) return await base.SendAsync(request, cancellationToken);
                        }
                    }
                }
                return request.CreateResponse(HttpStatusCode.Unauthorized);
            }
        }
复制代码

posted @   iDEAAM  阅读(445)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
历史上的今天:
2014-09-11 Microsoft Dynamics CRM 2011 面向Internet部署 (IFD) ADFS虚拟机环境搭建的步骤(CRM与ADFS装在同一台服务器上) 摘自网络
2012-09-11 Linq 左连接 内连接
2009-09-11 CSS滤镜使用方法汇总
点击右上角即可分享
微信分享提示