首页 新闻 会员 周边 捐助

ASP.NET Core 中通过 IP 地址访问也会强制跳转 https 的问题

0
悬赏园豆:30 [已解决问题] 解决于 2020-01-19 18:58

跳转 https 用的是 asp.net core 内置的 url 重写规则

var rewriteOptions = new RewriteOptions()
    .AddRedirectToHttpsPermanent();

发现通过 IP 地址访问也会强制跳转 https

curl -i http://192.168.107.240/metrics
HTTP/1.1 301 Moved Permanently
Date: Sat, 18 Jan 2020 03:23:06 GMT
Server: Kestrel
Content-Length: 0
Location: https://192.168.107.240/metrics

请问如何解决?

dudu的主页 dudu | 高人七级 | 园豆:29542
提问于:2020-01-18 11:32
< >
分享
最佳答案
0

AddRedirect 自己搞個rule,非ip才 to https

收获园豆:30
czd890 | 专家六级 |园豆:14488 | 2020-01-19 18:44

通过下面的 url 重写规则 RedirectToHttpsRule 实现了,ASP.NET Core 内置的 https 跳转组件的判断逻辑是只要 X-Forwarded-Proto 不是 https 就跳转,我觉得更合理的判断逻辑是只有 X-Forwarded-Proto 为 http 时才跳转,这样如果没有设置 X-Forwarded-Proto 就不会跳转。

RedirectToHttpsRule.cs

namespace Cnblogs.Web.Rewrite
{
    public class RedirectToHttpsRule : IRule
    {
        private const string HEADER_HAME = "X-Forwarded-Proto";

        public void ApplyRule(RewriteContext context)
        {
            var request = context.HttpContext.Request;

            if (request.Headers.TryGetValue(HEADER_HAME, out var forwardedProto))
            {
                if (forwardedProto.ToString() == "http")
                {
                    var isHttpGet = request.Method.Equals("get", StringComparison.OrdinalIgnoreCase);
                    var statusCode = isHttpGet ? StatusCodes.Status301MovedPermanently : StatusCodes.Status307TemporaryRedirect;

                    var host = context.HttpContext.Request.Host;
                    var newUrl = new StringBuilder()
                        .Append("https://")
                        .Append(host)
                        .Append(request.PathBase)
                        .Append(request.Path)
                        .Append(request.QueryString);

                    var response = context.HttpContext.Response;
                    response.StatusCode = statusCode;
                    response.Headers[HeaderNames.Location] = newUrl.ToString();
                    context.Result = RuleResult.EndResponse;
                }
            }
        }
    }
}

RewriteOptionsExtensions.cs

namespace Cnblogs.Web.Rewrite
{
    public static class RewriteOptionsExtensions
    {
        public static RewriteOptions AddCnblogsRedirectToHttps(this RewriteOptions options)
        {
            options.Rules.Add(new RedirectToHttpsRule());
            return options;
        }
    }
}

HttpsRedirectionBuilderExtensions.cs

namespace Microsoft.AspNetCore.Builder
{
    public static class HttpsRedirectionBuilderExtensions
    {
        public static IApplicationBuilder UseCnblogsHttpsRedirection(this IApplicationBuilder app)
        {
            app.UseRewriter(new RewriteOptions().AddCnblogsRedirectToHttps());
            return app;
        }
    }
}
dudu | 园豆:29542 (高人七级) | 2020-01-19 18:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册