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));
            }
        }
相關文章
相關標籤/搜索