Azure / api-management-samples

MIT License
138 stars 137 forks source link

Rest API sample token generation code is wrong #28

Open tmarkovski opened 5 years ago

tmarkovski commented 5 years ago

Sample is outdated, the working code to generate the SAS token is

static private string CreateSharedAccessToken(string id, string key, DateTime then)
{
    // Important: seconds must be 0 for this to work
    DateTime expiry = new DateTime(then.Year, then.Month, then.Day, then.Hour, then.Minute, 0, DateTimeKind.Utc);
    using (HMACSHA512 hmac = new HMACSHA512(Encoding.UTF8.GetBytes(key)))
    {
        string dataToSign = id + "\n" + expiry.ToString("O", CultureInfo.InvariantCulture);
        byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(dataToSign));
        string signature = Convert.ToBase64String(hash);
        return $"{id}&{expiry:yyyyMMddHHmm}&{signature}";
    }
}