ASP.NET WebAPI HTTPS


 
第一步 創建受信任的根證書頒發機構
 
makecert.exe -n "CN=Development CA" -r -sv DevelopmentCA.pvk DevelopmentCA.cer
 
並將證書導入到證書管理,特別要注意的是必須是“證書-本地計算機”,而非當前用戶
 
 
第二步 利用剛才創建的根證書來創建證書的pfx格式 ,第一條命令創建證書,第二條命令將轉換為pfx格式並包含私鑰,“123456”為私鑰密碼
 
makecert.exe -pe -n "CN=localhost" -a sha1 -sky exchange -eku 1.3.6.1.5.5.7.3.1 -ic DevelopmentCA.cer -iv developmentCA.pvk -sv SSLCert.pvk SSLCert.cer
 
pvk2pfx -pvk SSLCert.pvk -spc SSLCert.cer -pfx SSLCert.pfx -po 123456 
 
導入證書到本地計算機個人證書
 
第三步 生成客戶端證書,執行命令之后客戶端證書自動會添加到“證書-當前用戶”個人證書里
 
makecert.exe -pe -ss My -sr CurrentUser -a sha1 -sky exchange -n "CN=ClientCertificatesTest"
-eku 1.3.6.1.5.5.7.3.2 -sk SignedByCA -ic DevelopmentCA.cer -iv DevelopmentCA.pvk
 
 
 
 
第四步 證書生成完畢后配置IIS,在網站中添加綁定選擇https類型,SSL證書選擇我們剛才創建的
 
 
第五步 更改SSL設置,我這里是設置了必須要求SSL,可根據自己的實際情況來選擇
 
 
 
第六步  在程序中添加HTTPS過濾器,添加此特性的接口會先判斷請求是否來自HTTPS
 
publicclassRequireHttpsAttribute : AuthorizationFilterAttribute
    {
        publicoverridevoid OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
            {
                actionContext.Response = newHttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                {                 
                    ReasonPhrase = "HTTPS Required"
                };
            }
            else
            {
                base.OnAuthorization(actionContext);
            }
        }
    }
 
 
最后我們測試下SSL是否生效
 
 
 publicstaticvoid Test()
        {
            var secure = newSecureString();
            foreach (char s in"password") //password為導出的證書安全密碼
            {
                secure.AppendChar(s);
            }
            var handler = newWebRequestHandler();
            handler.ClientCertificateOptions = ClientCertificateOption.Manual;
            handler.UseProxy = false;

            string path = @"C:\test.pfx";
            var certificate = newX509Certificate2(path, secure);
            handler.ClientCertificates.Add(certificate);

            ServicePointManager
                .ServerCertificateValidationCallback +=
                (sender, cert, chain, sslPolicyErrors) => true;

            using (var client = newHttpClient(handler))
            using (var content = newMultipartFormDataContent())
            {
                var arg = 1;
                var url = string.Format(@" https://localhost:4438/api/test?arg={0}",arg);
                var result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync();
                Console.WriteLine(string.Format("[{0}]", result.Result));
            }
        }
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM