HTTP、HTTPS 头部标识
ELB 对 HTTPS 进行代理,无论是 HTTP 还是 HTTPS 请求,到了 ELB 转发给后端 ECS 时,都是 HTTP 请求。这使开发者无法分辨前端的请求是 HTTP 还是 HTTPS。
ELB 在将请求转发给后端 ECS 时,头部 header 会植入 X-Forwarded-Proto:
X-Forwarded-Proto: http (前端为 HTTP 请求)
X-Forwarded-Proto: https (前端为 HTTPS 请求)
DEMO: 判断负载均衡转发的是http,还是https请求,使用同样的协议访问。
(IsHttps(filterContext) ? "https" : "http") + loginUrl.Substring(loginUrl.IndexOf(":"));
/// <summary>
/// 判断当前请求是否为https
/// </summary>
/// <param name="filterContext"></param>
/// <returns></returns>
private bool IsHttps(AuthorizationFilterContext filterContext)
{
var request = filterContext.HttpContext.Request;
if (request.IsHttps)
{
return true;
}
var httpsTag = "https";
if (httpsTag.Equals(request.Scheme, StringComparison.OrdinalIgnoreCase))
{
return true;
}
foreach (var item in request.Headers)
{
if ("X-Forwarded-Proto".Equals(item.Key, StringComparison.OrdinalIgnoreCase))
{
if (StringValues.Equals(httpsTag, item.Value))
{
return true;
}
else
{
return false;
}
}
}
return false;
}