Last active
December 11, 2019 09:22
-
-
Save chocolatkey/e4a265ba5fc27b47ee8ab2e663fe4d62 to your computer and use it in GitHub Desktop.
Generate signed URIs for a client to access links secured with ngx_http_secure_link_module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Example of how to configure Nginx for signed urls. Make sure to replace YOUR_URL_SECRET_KEY_HERE with your url signing key | |
location /secrets/ { | |
# Headers for debugging | |
add_header X-Secure-Uri "$uri"; | |
add_header X-Secure-Ip "$remote_addr"; | |
add_header X-Secure-Expires "$arg_expires"; | |
# Secure URL | |
secure_link $arg_signature,$arg_expires; | |
secure_link_md5 "$uri|$remote_addr|$secure_link_expires|YOUR_URL_SECRET_KEY_HERE"; | |
if ($secure_link = "") { return 403; } # Access denied | |
if ($secure_link = "0") { return 410; } # Gone, meaning expired | |
} | |
**/ | |
func getUserIp(req *http.Request) (net.IP, error) { | |
ip, _, err := net.SplitHostPort(req.RemoteAddr) | |
if err != nil { | |
return nil, fmt.Errorf("failed to split remote address %q", req.RemoteAddr) | |
} | |
userIP := net.ParseIP(ip) | |
if userIP == nil { | |
return nil, fmt.Errorf("failed to parse remote address %q", req.RemoteAddr) | |
} | |
return userIP, nil | |
} | |
const secret = "YOUR_URL_SECRET_KEY_HERE" | |
var urlSignatureFormat = template.Must(template.New("urlsecret").Parse("{{.uri}}|{{.addr}}|{{.expiry}}|{{.secret}}")) | |
func signUri(uri string, req *http.Request, expiry time.Time) (string, error) { | |
ip, err := getUserIp(req) | |
if err != nil { | |
return "", err | |
} | |
epochtime := expiry.Unix() | |
m := map[string]interface{}{"uri": uri, "addr": ip.String(), "expiry": epochtime, "secret": secret} | |
buf := &bytes.Buffer{} | |
err = urlSignatureFormat.Execute(buf, m) | |
if err != nil { | |
return "", err | |
} | |
hash := md5.Sum(buf.Bytes()) | |
return fmt.Sprintf("%s?signature=%s&expires=%d", uri, base64.RawURLEncoding.EncodeToString(hash[:]), epochtime), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment