非對稱認證方式 可以用在 asp.net webapi 的安全機制裡面

來源:互聯網
上載者:User

標籤:

 //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);            }        }

非對稱認證方式 可以用在 asp.net webapi 的安全機制裡面

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.