[英]Configuring SSL on ASP.NET Self-Hosted Web API
我正在創建自托管Web API服務。 為了保護它,我已經研究並實現了這篇文章,使用makecert成功生成了本地SSL證書並且我的服務已經過身份驗證,如果我正在使用,則會生成令牌。
http://localhost/webapi/authentication/authenticate
鏈接,但是當我嘗試使用HTTPS訪問我的服務時,我會在Firefox上關注:
SSL_ERROR_RX_RECORD_TOO_LONG
而對於同樣的要求,Fiddler告訴我:
HTTP / 1.1 502 Fiddler - 連接失敗日期:2013年8月26日星期一10:44:27 GMT內容類型:text / html; charset = UTF-8連接:關閉時間戳:13:44:27.433
[Fiddler]與localhost的套接字連接失敗。
無法與server.fiddler.network.https協商HTTPS連接>無法保護localhost的現有連接。 由於意外的數據包格式,握手失敗。
我的自主配置:
private HttpSelfHostServer _server;
private ExtendedHttpsSelfHostConfiguration _config;
public const string ServiceAddress = "https://localhost/webapi";
_config = new ExtendedHttpsSelfHostConfiguration(ServiceAddress);
_server = new HttpSelfHostServer(_config);
_server.OpenAsync();
從這篇文章中獲取的ExtendedHttpSelfHostConfiguration是:
public class ExtendedHttpSelfHostConfiguration : HttpSelfHostConfiguration
{
public ExtendedHttpSelfHostConfiguration(string baseAddress) : base(baseAddress) { }
public ExtendedHttpSelfHostConfiguration(Uri baseAddress) : base(baseAddress) { }
protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
{
if (BaseAddress.ToString().ToLower().Contains("https://"))
{
httpBinding.Security.Mode = HttpBindingSecurityMode.Transport;
}
return base.OnConfigureBinding(httpBinding);
}
}
我錯過了什么? 提前致謝!
根據我發現的這篇博文 ,我應該創建一個SSL證書並將其分配給特定端口(在我的情況下為99)。
我已經創建了本地簽名的SSL。 然后得到它的Thumbprint和ApplicationId 。 使用CMD命令netsh (在Win7之前的系統中有一個httpcfg工具),我已經將我的證書分配給了端口
netsh http add sslcert ipport=0.0.0.0:99 certhash=3e49906c01a774c888231e5092077d3d855a6861 appid={2d6059b2-cccb-4a83-ae08-8ce209c2c5c1}
,其中certhash = SSL Thumbprint ,appid = ApplicationId我之前已經復制過。
就是這樣,現在我能夠發出HTTPS請求了!
將使用您指定的名稱創建證書,然后找到它。
現在您已經創建了證書,是時候將它綁定到您在自托管中使用的端口了。 如果它是https:// localhost:5000
netsh http add sslcert ipport=0.0.0.0:5000 certhash=[cert-thumbprint] appid={[App-Id]}
[assembly: Guid("[app-id]")]
你完成了!
使用Code的第一種方法:
public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
actionContext.Response = actionContext.Request
.CreateResponse(HttpStatusCode.Found);
actionContext.Response.Content = new StringContent
("<did>Use https instead of http</div>", Encoding.UTF8, "text/html");
UriBuilder uriBuilder = new UriBuilder(actionContext.Request.RequestUri);
uriBuilder.Scheme = Uri.UriSchemeHttps;
uriBuilder.Port = 44337;
actionContext.Response.Headers.Location = uriBuilder.Uri;
}
else
{
base.OnAuthorization(actionContext);
}
}
}
在web配置文件中輸入以下代碼:
config.Filters.Add(new RequireHttpsAttribute());
使用Attribute的第二種方法:如果您不想使用第一種方法,可以使用RequireHttpsAttribute
修飾控制器類或操作方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.