標籤:
參照文檔 http://southworks.com/blog/2014/06/16/enabling-ssl-client-certificates-in-asp-net-web-api/ 第一步 建立可信任的根憑證授權單位 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));
} }
ASP.NET WebAPI HTTPS