gpt4 book ai didi

c# - 使用反向代理在服务中强制执行 SSL

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:07 25 4
gpt4 key购买 nike

基于文章Working with SSL in Web API我实现了一个授权过滤器,要求 SSL 用于 Web API (2.1) Controller 的方法:

[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 Farm Framework (WFF) 用作反向代理,它可能会失败(通过阻止有效的 HTTPS 请求)。

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

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

最佳答案

这是我想出的:

/// <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;
}
}

关于c# - 使用反向代理在服务中强制执行 SSL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24659804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com