C# 如何使用 web.config 文件强制使用 HTTPS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9823010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 10:46:09  来源:igfitidea点击:

How to force HTTPS using a web.config file

c#asp.netiishttpsweb-config

提问by Ben Carey

I have searched around Google and StackOverflow trying to find a solution to this, but they all seem to relate to ASP.NET etc.

我在 Google 和 StackOverflow 上四处搜索,试图找到解决方案,但它们似乎都与 ASP.NET 等有关。

I usually run Linux on my servers but for this one client I am using Windows with IIS 7.5 (and Plesk 10). This being the reason why I am slightly unfamiliar with IIS and web.configfiles. In an .htaccessfile you can use rewrite conditions to detect whether the protocol is HTTPS and redirect accordingly. Is there a simple wayto achieve this using a web.config file, or even using the 'URL Rewrite' module that I have installed?

我通常在我的服务器上运行 Linux,但对于这个客户端,我使用的是带有 IIS 7.5(和 Plesk 10)的 Windows。这就是为什么我对 IIS 和 web.config文件有点不熟悉的原因。在.htaccess文件中,您可以使用重写条件来检测协议是否为 HTTPS 并相应地重定向。有没有一种简单的方法可以使用 web.config 文件甚至使用我安装的“ URL Rewrite”模块来实现这一点?

I have no experience with ASP.NETso if this is involved in the solution then please include clear steps of how to implement.

没有使用 ASP.NET 的经验,所以如果这涉及到解决方案,那么请包括如何实施的明确步骤。

The reason for me doing this with the web.config and notPHP is that I would like to force HTTPS on all assets within the site.

我使用 web.config 而不是PHP这样做的原因是我想在站点内的所有资产上强制使用 HTTPS。

采纳答案by LazyOne

You need URL Rewrite module, preferably v2 (I have no v1 installed, so cannot guarantee that it will work there, but it should).

你需要 URL Rewrite 模块,最好是 v2(我没有安装 v1,所以不能保证它会在那里工作,但它应该)。

Here is an example of such web.config -- it will force HTTPS for ALL resources (using 301 Permanent Redirect):

这是此类 web.config 的示例——它将强制所有资源使用 HTTPS(使用 301 永久重定向):

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <clear />
                <rule name="Redirect to https" stopProcessing="true">
                    <match url=".*" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

P.S.This particular solution has nothing to do with ASP.NET/PHP or any other technology as it's done using URL rewriting module only -- it is processed at one of the initial/lower levels -- before request gets to the point where your code gets executed.

PS这个特定的解决方案与 ASP.NET/PHP 或任何其他技术无关,因为它仅使用 URL 重写模块完成 - 它在初始/较低级别之一进行处理 - 在请求到达您的代码之前被执行。

回答by redirect

A simple wayis to tell IIS to send your custom error file for HTTP requests. The file can then contain a meta redirect, a JavaScript redirect and instructions with link, etc... Importantly, you can still check "Require SSL" for the site (or folder) and this will work.

一个简单的方法是告诉 IIS 发送 HTTP 请求的自定义错误文件。然后,该文件可以包含元重定向、JavaScript 重定向和带链接的说明等...重要的是,您仍然可以为站点(或文件夹)选中“需要 SSL”,这将起作用。

</configuration>
</system.webServer>
    <httpErrors>
        <clear/>
        <!--redirect if connected without SSL-->
        <error statusCode="403" subStatusCode="4" path="errors3.4_requiressl.html" responseMode="File"/>
    </httpErrors>
</system.webServer>
</configuration>

回答by Muhammad Rehan Saeed

For those using ASP.NET MVC. You can use the RequireHttpsAttributeto force all responses to be HTTPS:

对于那些使用 ASP.NET MVC 的人。您可以使用RequireHttpsAttribute强制所有响应为 HTTPS:

GlobalFilters.Filters.Add(new RequireHttpsAttribute());

Other things you may also want to do to help secure your site:

您可能还想要做的其他事情来帮助保护您的网站:

  1. Force Anti-Forgery tokens to use SSL/TLS:

    AntiForgeryConfig.RequireSsl = true;
    
  2. Require Cookies to require HTTPS by default by changing the Web.config file:

    <system.web>
        <httpCookies httpOnlyCookies="true" requireSSL="true" />
    </system.web>
    
  3. Use the NWebSec.OwinNuGet package and add the following line of code to enable Strict Transport Security (HSTS) across the site. Don't forget to add the Preload directive below and submit your site to the HSTS Preload site. More information hereand here. Note that if you are not using OWIN, there is a Web.config method you can read up on on the NWebSecsite.

    // app is your OWIN IAppBuilder app in Startup.cs
    app.UseHsts(options => options.MaxAge(days: 720).Preload());
    
  4. Use the NWebSec.Owin NuGet package and add the following line of code to enable Public Key Pinning (HPKP) across the site. More information hereand here.

    // app is your OWIN IAppBuilder app in Startup.cs
    app.UseHpkp(options => options
        .Sha256Pins(
            "Base64 encoded SHA-256 hash of your first certificate e.g. cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=",
            "Base64 encoded SHA-256 hash of your second backup certificate e.g. M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE=")
        .MaxAge(days: 30));
    
  5. Include the https scheme in any URL's used. Content Security Policy (CSP)HTTP header and Subresource Integrity (SRI)do not play nice when you imit the scheme in some browsers. It is better to be explicit about HTTPS. e.g.

    <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.4/bootstrap.min.js">
    </script>
    
  6. Use the ASP.NET MVC BoilerplateVisual Studio project template to generate a project with all of this and much more built in. You can also view the code on GitHub.

  1. 强制防伪令牌使用 SSL/TLS:

    AntiForgeryConfig.RequireSsl = true;
    
  2. 通过更改 Web.config 文件,默认情况下需要 Cookie 需要 HTTPS:

    <system.web>
        <httpCookies httpOnlyCookies="true" requireSSL="true" />
    </system.web>
    
  3. 使用NWebSec.OwinNuGet 包并添加以下代码行以启用跨站点的严格传输安全 (HSTS)。不要忘记添加下面的 Preload 指令并将您的站点提交到HSTS Preload 站点。更多信息在这里这里。请注意,如果您没有使用 OWIN,则可以在NWebSec站点上阅读 Web.config 方法。

    // app is your OWIN IAppBuilder app in Startup.cs
    app.UseHsts(options => options.MaxAge(days: 720).Preload());
    
  4. 使用 NWebSec.Owin NuGet 包并添加以下代码行以启用整个站点的公钥固定 (HPKP)。更多信息在这里这里

    // app is your OWIN IAppBuilder app in Startup.cs
    app.UseHpkp(options => options
        .Sha256Pins(
            "Base64 encoded SHA-256 hash of your first certificate e.g. cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=",
            "Base64 encoded SHA-256 hash of your second backup certificate e.g. M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE=")
        .MaxAge(days: 30));
    
  5. 在使用的任何 URL 中包含 https 方案。当您在某些浏览器中模仿该方案时,内容安全策略 (CSP)HTTP 标头和子资源完整性 (SRI) 效果不佳。最好明确说明 HTTPS。例如

    <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.4/bootstrap.min.js">
    </script>
    
  6. 使用ASP.NET MVC BoilerplateVisual Studio 项目模板生成包含所有这些以及更多内置功能的项目。您还可以在GitHub 上查看代码。

回答by WhatIsHeDoing

The excellent NWebseclibrary can upgrade your requests from HTTP to HTTPS using its upgrade-insecure-requeststag within the Web.config:

优秀的NWebsec库可以使用以下upgrade-insecure-requests标签将您的请求从 HTTP 升级到 HTTPS Web.config

<nwebsec>
  <httpHeaderSecurityModule>
    <securityHttpHeaders>
      <content-Security-Policy enabled="true">
        <upgrade-insecure-requests enabled="true"  />
      </content-Security-Policy>
    </securityHttpHeaders>
  </httpHeaderSecurityModule>
</nwebsec>

回答by Shaun Luttin

To augment LazyOne's answer, here is an annotated version of the answer.

为了增加 LazyOne 的答案,这里是答案的注释版本。

<rewrite>
  <rules>
     <clear />
     <rule name="Redirect all requests to https" stopProcessing="true">
       <match url="(.*)" />
         <conditions logicalGrouping="MatchAll">
           <add input="{HTTPS}" pattern="off" ignoreCase="true" />
         </conditions>
         <action 
            type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" 
            redirectType="Permanent" appendQueryString="false" />
     </rule>
  </rules>
</rewrite>

Clear all the other rules that might already been defined on this server. Create a new rule, that we will name "Redirect all requests to https". After processing this rule, do not process any more rules! Match all incoming URLs. Then check whether all of these other conditions are true: HTTPS is turned OFF. Well, that's only one condition (but make sure it's true). If it is, send a 301 Permanent redirect back to the client at http://www.foobar.com/whatever?else=the#url-contains. Don't add the query string at the end of that, because it would duplicate the query string!

清除可能已在此服务器上定义的所有其他规则。创建一个新规则,我们将命名为“将所有请求重定向到 https”。处理完这条规则后,不要再处理任何规则!匹配所有传入的 URL。然后检查所有这些其他条件是否都为真:HTTPS 已关闭。嗯,这只是一个条件(但要确保它是真的)。如果是,则将 301 永久重定向发送回客户端http://www.foobar.com/whatever?else=the#url-contains。不要在末尾添加查询字符串,因为它会重复查询字符串!

This is what the properties, attributes, and some of the values mean.

这就是属性、属性和某些值的含义。

  • clearremoves all server rules that we might otherwise inherit.
  • ruledefines a rule.
    • namean arbitrary (though unique) name for the rule.
    • stopProcessingwhether to forward the request immediately to the IIS request pipeline or first to process additional rules.
  • matchwhen to run this rule.
    • urla pattern against which to evaluate the URL
  • conditionsadditional conditions about when to run this rule; conditions are processed only if there is first a match.
    • logicalGroupingwhether all the conditions must be true (MatchAll) or any of the conditions must be true (MatchAny); similar to AND vs OR.
  • addadds a condition that must be met.
    • inputthe input that a condition is evaluating; input can be server variables.
    • patternthe standard against which to evaluate the input.
    • ignoreCasewhether capitalization matters or not.
  • actionwhat to do if the matchand its conditionsare all true.
    • typecan generally be redirect(client-side) or rewrite(server-side).
    • urlwhat to produce as a result of this rule; in this case, concatenate https://with two server variables.
    • redirectTypewhat HTTP redirect to use; this one is a 301 Permanent.
    • appendQueryStringwhether to add the query string at the end of the resultant urlor not; in this case, we are setting it to false, because the {REQUEST_URI}already includes it.
  • clear删除我们可能会继承的所有服务器规则。
  • rule定义规则。
    • 为规则命名一个任意(虽然唯一)的名称。
    • stopProcessing是立即将请求转发到 IIS 请求管道还是首先处理其他规则。
  • 匹配何时运行此规则。
    • url评估 URL 的模式
  • 条件有关何时运行此规则的附加条件;仅当第一个匹配项时才处理条件。
    • 逻辑分组是否所有条件都必须为真(MatchAll)或任何条件必须为真(MatchAny);类似于 AND 与 OR。
  • add添加一个必须满足的条件。
    • 输入条件正在评估的输入;输入可以是服务器变量。
    • 模式评估输入的标准。
    • ignoreCase 大小写是否重要。
  • action如果match和它conditions都是真的,该怎么办。
    • 类型通常可以是redirect(客户端)或rewrite(服务器端)。
    • url由于此规则而产生的结果;在这种情况下,连接https://两个服务器变量。
    • 重定向输入要使用的 HTTP 重定向;这是一个 301 永久的。
    • appendQueryString是否在结果末尾添加查询字符串url;在这种情况下,我们将其设置为 false,因为{REQUEST_URI}已经包含它。

The server variables are

服务器变量是

  • {HTTPS}which is either OFFor ON.
  • {HTTP_HOST}is www.mysite.com, and
  • {REQUEST_URI}includes the rest of the URI, e.g. /home?key=value
    • the browser handles the #fragment(see comment from LazyOne).
  • {HTTPS}其是OFFON
  • {HTTP_HOST}www.mysite.com,并且
  • {REQUEST_URI}包括 URI 的其余部分,例如 /home?key=value
    • 浏览器处理#fragment(参见来自 LazyOne 的评论)。

See also: https://www.iis.net/learn/extensions/url-rewrite-module/url-rewrite-module-configuration-reference

另见:https: //www.iis.net/learn/extensions/url-rewrite-module/url-rewrite-module-configuration-reference

回答by Eric

The accepted answer did not work for me. I followed the steps on this blog.

接受的答案对我不起作用。我按照此博客上的步骤操作。

A key point that was missing for me was that I needed to download and install the URL Rewrite Tool for IIS. I found it here.The result was the following.

我缺少的一个关键点是我需要下载并安装用于 IIS 的 URL 重写工具。我在这里找到结果如下。

<rewrite>
        <rules>
            <remove name="Http to Https" />
            <rule name="Http to Https" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
                <match url="*" />
                <conditions>
                    <add input="{HTTPS}" pattern="off" />
                </conditions>
                <serverVariables />
                <action type="Redirect" url="https://{HTTPS_HOST}{REQUEST_URI}" />
            </rule>
        </rules>
    </rewrite>

回答by Spencer Sullivan

I was not allowed to install URL Rewrite in my environment, so, I found another path.

我不允许在我的环境中安装 URL Rewrite,所以,我找到了另一个路径。

Adding this to my web.config added the error rewrite and worked on IIS 7.5:

将此添加到我的 web.config 添加了错误重写并在 IIS 7.5 上工作:

<system.webServer>
    <httpErrors errorMode="Custom" defaultResponseMode="File" defaultPath="C:\WebSites\yoursite\" >    
    <remove statusCode="403" subStatusCode="4" />
    <error statusCode="403" subStatusCode="4" responseMode="File" path="redirectToHttps.html" />
</httpErrors>

Then, following the advice here: https://www.sslshopper.com/iis7-redirect-http-to-https.html

然后,按照这里的建议:https: //www.sslshopper.com/iis7-redirect-http-to-https.html

I created the html file that does the redirect (redirectToHttps.html):

我创建了执行重定向的 html 文件 (redirectToHttps.html):

<html>
<head><title>Redirecting...</title></head>
<script language="JavaScript">
function redirectHttpToHttps()
{
    var httpURL= window.location.hostname + window.location.pathname + window.location.search;
    var httpsURL= "https://" + httpURL;
    window.location = httpsURL;
}
redirectHttpToHttps();
</script>
<body>
</body>
</html>

I hope someone finds this useful as I could not find all of the pieces in one place anywhere else.

我希望有人觉得这很有用,因为我无法在其他任何地方的一个地方找到所有作品。

回答by Oracular Man

In .Net Core, follow the instructions at https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl

在 .Net Core 中,按照https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl 中的说明进行操作

In your startup.cs add the following:

在您的 startup.cs 中添加以下内容:

// Requires using Microsoft.AspNetCore.Mvc;
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new RequireHttpsAttribute());
    });`enter code here`

To redirect Http to Https, add the following in the startup.cs

要将 Http 重定向到 Https,请在 startup.cs 中添加以下内容

// Requires using Microsoft.AspNetCore.Rewrite;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    var options = new RewriteOptions()
       .AddRedirectToHttps();

    app.UseRewriter(options);