-
-
Save tsungtwu/2a3afe619a806a82c74f47a02e36bd53 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