使用反向代理在服务中实施SSL

时间:2014-07-09 17:08:33

标签: c# ssl asp.net-web-api reverse-proxy web-farm-framework

根据文章Working with SSL in Web API,我实施了一个授权过滤器,要求为Web API(2.1)控制器的方法使用SSL:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true,
                AllowMultiple = false)]
public sealed class RequireHttpsAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden)
                                         {
                                             ReasonPhrase = "HTTPS Required"
                                         };
        }
        else
        {
            base.OnAuthorization(actionContext);
        }
    }
}

这在某些Web服务器上运行良好。如果Web Farm Framework(WFF)用作反向代理,则可能会失败(通过阻止有效的HTTPS请求)。

WFF添加标题X-Forwarded-Proto,这是反向代理的事实标准。

如何修改此代码以使用或不使用标准代理?

1 个答案:

答案 0 :(得分:1)

以下是我提出的建议:

/// <summary>
/// Action filter to require SSL for a protected resource.
/// </summary>
/// <remarks>
/// From http://www.asp.net/web-api/overview/security/working-with-ssl-in-web-api
/// but modified to support reverse proxies such as Web Farm Framework.
/// </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class RequireHttpsAttribute : AuthorizationFilterAttribute
{
    [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Not possible.")]
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (IsSecure(actionContext.Request))
        {
            base.OnAuthorization(actionContext);
        }
        else
        {
            actionContext.Response =
                new HttpResponseMessage(HttpStatusCode.Forbidden)
                    {
                        ReasonPhrase = "HTTPS Required"
                    };
        }
    }

    private static bool IsSecure(HttpRequestMessage request)
    {
        if (request.RequestUri.Scheme == Uri.UriSchemeHttps)
        {
            return true;
        }

        IEnumerable<string> headerValues;

        if (request.Headers.TryGetValues("X-Forwarded-Proto", out headerValues))
        {
            string protocol = headerValues.FirstOrDefault();

            return string.Equals(protocol, "https", StringComparison.OrdinalIgnoreCase);
        }

        return false;
    }
}