Created
January 10, 2019 08:14
-
-
Save dennis-tra/14c63e6359f17cbb504e78d6740ca465 to your computer and use it in GitHub Desktop.
A little helper function to generate the shared access token (SAS) to talk to e.g. Azure Notification Hubs
This file contains 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
package main | |
import ( | |
"crypto/hmac" | |
"crypto/sha256" | |
"encoding/base64" | |
"fmt" | |
"net/url" | |
"strconv" | |
"text/template" | |
"time" | |
) | |
const day = time.Minute * 60 * 24 | |
func main() { | |
SaS := createSharedAccessToken("<ServiceBusURL>", "<PolicyName>", "<SecretKey>") | |
fmt.Println(SaS) | |
} | |
// createSharedAccessToken generates the "Authorization" header value necessary to talk | |
// to Azure Notification Hubs. The parameter uri corresponds to the resource | |
// you send the request to. E.g.: | |
// https://mysite.servicebus.windows.net/mysite-notif/registrations/?api-version=2015-01 | |
// | |
// You will get the other parameters from the notification hub access | |
// policies connection string. E.g: | |
// Endpoint=sb://long-url.servicebus.windows.net/;SharedAccessKeyName=ABC;SharedAccessKey=XYZ | |
func createSharedAccessToken(uri string, sharedAccessKeyName string, sharedAccessKey string) string { | |
// expiry date is set to a time in the future. In the following example it is one day | |
// https://code.msdn.microsoft.com/Shared-Access-Signature-0a88adf8 | |
expiry := time.Now().Add(day).Unix() | |
expiryStr := strconv.FormatInt(expiry, 10) | |
// construct the string we need to sign with HMAC SHA256 | |
stringToSign := template.URLQueryEscaper(uri) + "\n" + expiryStr | |
// Generate the signature of the above string | |
hash := hmac.New(sha256.New, []byte(sharedAccessKey)) | |
hash.Write([]byte(stringToSign)) | |
signature := base64.StdEncoding.EncodeToString(hash.Sum(nil)) | |
q := url.Values{} | |
q.Add("sr", uri) | |
q.Add("sig", signature) | |
q.Add("se", expiryStr) | |
q.Add("skn", sharedAccessKeyName) | |
// construct the shared access signature token | |
return "SharedAccessSignature " + q.Encode() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment