Files

27 lines
761 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package web
import (
"net"
"net/http"
"strings"
)
// requestIsHTTPS 识别直连 TLS,或仅信任本机反向代理传入的 HTTPS 标记。
// Admin 生产进程只监听 127.0.0.1,Nginx 在同机终止 TLS;不能无条件信任
// X-Forwarded-Proto,否则直接访问端口的客户端可以伪造安全来源。
func requestIsHTTPS(request *http.Request) bool {
if request.TLS != nil {
return true
}
host, _, err := net.SplitHostPort(request.RemoteAddr)
if err != nil {
return false
}
remoteIP := net.ParseIP(host)
if remoteIP == nil || !remoteIP.IsLoopback() {
return false
}
forwardedProto := strings.TrimSpace(strings.Split(request.Header.Get("X-Forwarded-Proto"), ",")[0])
return strings.EqualFold(forwardedProto, "https")
}