| | 1 | | // Copyright (c) Microsoft. All rights reserved. |
| | 2 | | // Licensed under the MIT license. See LICENSE file in the project root for full license information. |
| | 3 | |
|
| | 4 | | namespace Microsoft.Azure.ServiceBus.Primitives |
| | 5 | | { |
| | 6 | | using System; |
| | 7 | | using System.Collections.Generic; |
| | 8 | | using System.Diagnostics.CodeAnalysis; |
| | 9 | | using System.Globalization; |
| | 10 | | using System.Net; |
| | 11 | | using System.Security.Cryptography; |
| | 12 | | using System.Text; |
| | 13 | | using System.Threading.Tasks; |
| | 14 | |
|
| | 15 | | /// <summary> |
| | 16 | | /// The SharedAccessSignatureTokenProvider generates tokens using a shared access key or existing signature. |
| | 17 | | /// </summary> |
| | 18 | | public class SharedAccessSignatureTokenProvider : TokenProvider |
| | 19 | | { |
| | 20 | | const TokenScope DefaultTokenScope = TokenScope.Entity; |
| | 21 | |
|
| 2 | 22 | | internal static readonly TimeSpan DefaultTokenTTL = TimeSpan.FromMinutes(60); |
| | 23 | |
|
| | 24 | | readonly byte[] encodedSharedAccessKey; |
| | 25 | | readonly string keyName; |
| | 26 | | readonly TimeSpan tokenTimeToLive; |
| | 27 | | readonly TokenScope tokenScope; |
| | 28 | | readonly string sharedAccessSignature; |
| 2 | 29 | | internal static readonly Func<string, byte[]> MessagingTokenProviderKeyEncoder = Encoding.UTF8.GetBytes; |
| | 30 | |
|
| 0 | 31 | | internal SharedAccessSignatureTokenProvider(string sharedAccessSignature) |
| | 32 | | { |
| 0 | 33 | | SharedAccessSignatureToken.Validate(sharedAccessSignature); |
| 0 | 34 | | this.sharedAccessSignature = sharedAccessSignature; |
| 0 | 35 | | } |
| | 36 | |
|
| | 37 | | internal SharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, TokenScope tokenScope = Toke |
| 14 | 38 | | : this(keyName, sharedAccessKey, MessagingTokenProviderKeyEncoder, DefaultTokenTTL, tokenScope) |
| | 39 | | { |
| 14 | 40 | | } |
| | 41 | |
|
| | 42 | | internal SharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, TimeSpan tokenTimeToLive, To |
| 0 | 43 | | : this(keyName, sharedAccessKey, MessagingTokenProviderKeyEncoder, tokenTimeToLive, tokenScope) |
| | 44 | | { |
| 0 | 45 | | } |
| | 46 | |
|
| | 47 | | /// <summary></summary> |
| | 48 | | /// <param name="keyName"></param> |
| | 49 | | /// <param name="sharedAccessKey"></param> |
| | 50 | | /// <param name="customKeyEncoder"></param> |
| | 51 | | /// <param name="tokenTimeToLive"></param> |
| | 52 | | /// <param name="tokenScope"></param> |
| 14 | 53 | | protected SharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, Func<string, byte[]> custom |
| | 54 | | { |
| 14 | 55 | | if (string.IsNullOrEmpty(keyName)) |
| | 56 | | { |
| 0 | 57 | | throw new ArgumentNullException(nameof(keyName)); |
| | 58 | | } |
| | 59 | |
|
| 14 | 60 | | if (keyName.Length > SharedAccessSignatureToken.MaxKeyNameLength) |
| | 61 | | { |
| 0 | 62 | | throw new ArgumentOutOfRangeException( |
| 0 | 63 | | nameof(keyName), |
| 0 | 64 | | Resources.ArgumentStringTooBig.FormatForUser(nameof(keyName), SharedAccessSignatureToken.MaxKeyNameL |
| | 65 | | } |
| | 66 | |
|
| 14 | 67 | | if (string.IsNullOrEmpty(sharedAccessKey)) |
| | 68 | | { |
| 0 | 69 | | throw new ArgumentNullException(nameof(sharedAccessKey)); |
| | 70 | | } |
| | 71 | |
|
| 14 | 72 | | if (sharedAccessKey.Length > SharedAccessSignatureToken.MaxKeyLength) |
| | 73 | | { |
| 0 | 74 | | throw new ArgumentOutOfRangeException( |
| 0 | 75 | | nameof(sharedAccessKey), |
| 0 | 76 | | Resources.ArgumentStringTooBig.FormatForUser(nameof(sharedAccessKey), SharedAccessSignatureToken.Max |
| | 77 | | } |
| | 78 | |
|
| 14 | 79 | | this.keyName = keyName; |
| 14 | 80 | | this.tokenTimeToLive = tokenTimeToLive; |
| 14 | 81 | | this.encodedSharedAccessKey = customKeyEncoder != null ? |
| 14 | 82 | | customKeyEncoder(sharedAccessKey) : |
| 14 | 83 | | MessagingTokenProviderKeyEncoder(sharedAccessKey); |
| 14 | 84 | | this.tokenScope = tokenScope; |
| 14 | 85 | | } |
| | 86 | |
|
| | 87 | | /// <summary> |
| | 88 | | /// Gets a <see cref="SecurityToken"/> for the given audience and duration. |
| | 89 | | /// </summary> |
| | 90 | | /// <param name="appliesTo">The URI which the access token applies to. If <see cref="SharedAccessSignatureTokenP |
| | 91 | | /// is initiated with SASKeyName and SASKey, the token will be generated for this uri. If initiated with SASToke |
| | 92 | | /// the value is ignored.</param> |
| | 93 | | /// <param name="timeout">The timeout value for how long it takes to get the security token (not the token time |
| | 94 | | /// For SAS token, no asynchronous operation takes place and hence this timeout is ignored.</param> |
| | 95 | | /// <remarks>This parameter <paramref name="timeout"/> is here for compatibility, but is not currently used.</re |
| | 96 | | /// <returns><see cref="SecurityToken"/></returns> |
| | 97 | | public override Task<SecurityToken> GetTokenAsync(string appliesTo, TimeSpan timeout) |
| | 98 | | { |
| 0 | 99 | | TimeoutHelper.ThrowIfNegativeArgument(timeout); |
| 0 | 100 | | appliesTo = NormalizeAppliesTo(appliesTo); |
| 0 | 101 | | string tokenString = this.BuildSignature(appliesTo); |
| 0 | 102 | | var securityToken = new SharedAccessSignatureToken(tokenString); |
| 0 | 103 | | return Task.FromResult<SecurityToken>(securityToken); |
| | 104 | | } |
| | 105 | |
|
| | 106 | | /// <summary></summary> |
| | 107 | | /// <param name="targetUri"></param> |
| | 108 | | /// <returns></returns> |
| | 109 | | protected virtual string BuildSignature(string targetUri) |
| | 110 | | { |
| 0 | 111 | | return string.IsNullOrWhiteSpace(this.sharedAccessSignature) |
| 0 | 112 | | ? SharedAccessSignatureBuilder.BuildSignature( |
| 0 | 113 | | this.keyName, |
| 0 | 114 | | this.encodedSharedAccessKey, |
| 0 | 115 | | targetUri, |
| 0 | 116 | | this.tokenTimeToLive) |
| 0 | 117 | | : this.sharedAccessSignature; |
| | 118 | | } |
| | 119 | |
|
| | 120 | | string NormalizeAppliesTo(string appliesTo) |
| | 121 | | { |
| 0 | 122 | | return ServiceBusUriHelper.NormalizeUri(appliesTo, "https", true, stripPath: this.tokenScope == TokenScope.N |
| | 123 | | } |
| | 124 | |
|
| | 125 | | static class SharedAccessSignatureBuilder |
| | 126 | | { |
| | 127 | | [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "Uris are |
| | 128 | | public static string BuildSignature( |
| | 129 | | string keyName, |
| | 130 | | byte[] encodedSharedAccessKey, |
| | 131 | | string targetUri, |
| | 132 | | TimeSpan timeToLive) |
| | 133 | | { |
| | 134 | | // Note that target URI is not normalized because in IoT scenario it |
| | 135 | | // is case sensitive. |
| 0 | 136 | | string expiresOn = BuildExpiresOn(timeToLive); |
| 0 | 137 | | string audienceUri = WebUtility.UrlEncode(targetUri); |
| 0 | 138 | | List<string> fields = new List<string> { audienceUri, expiresOn }; |
| | 139 | |
|
| | 140 | | // Example string to be signed: |
| | 141 | | // http://mynamespace.servicebus.windows.net/a/b/c?myvalue1=a |
| | 142 | | // <Value for ExpiresOn> |
| 0 | 143 | | string signature = Sign(string.Join("\n", fields), encodedSharedAccessKey); |
| | 144 | |
|
| | 145 | | // Example returned string: |
| | 146 | | // SharedAccessKeySignature |
| | 147 | | // sr=ENCODED(http://mynamespace.servicebus.windows.net/a/b/c?myvalue1=a)&sig=<Signature>&se=<ExpiresOnV |
| | 148 | |
|
| 0 | 149 | | return string.Format(CultureInfo.InvariantCulture, "{0} {1}={2}&{3}={4}&{5}={6}&{7}={8}", |
| 0 | 150 | | SharedAccessSignatureToken.SharedAccessSignature, |
| 0 | 151 | | SharedAccessSignatureToken.SignedResource, audienceUri, |
| 0 | 152 | | SharedAccessSignatureToken.Signature, WebUtility.UrlEncode(signature), |
| 0 | 153 | | SharedAccessSignatureToken.SignedExpiry, WebUtility.UrlEncode(expiresOn), |
| 0 | 154 | | SharedAccessSignatureToken.SignedKeyName, WebUtility.UrlEncode(keyName)); |
| | 155 | | } |
| | 156 | |
|
| | 157 | | static string BuildExpiresOn(TimeSpan timeToLive) |
| | 158 | | { |
| 0 | 159 | | DateTime expiresOn = DateTime.UtcNow.Add(timeToLive); |
| 0 | 160 | | TimeSpan secondsFromBaseTime = expiresOn.Subtract(Constants.EpochTime); |
| 0 | 161 | | long seconds = Convert.ToInt64(secondsFromBaseTime.TotalSeconds, CultureInfo.InvariantCulture); |
| 0 | 162 | | return Convert.ToString(seconds, CultureInfo.InvariantCulture); |
| | 163 | | } |
| | 164 | |
|
| | 165 | | static string Sign(string requestString, byte[] encodedSharedAccessKey) |
| | 166 | | { |
| 0 | 167 | | using (var hmac = new HMACSHA256(encodedSharedAccessKey)) |
| | 168 | | { |
| 0 | 169 | | return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(requestString))); |
| | 170 | | } |
| 0 | 171 | | } |
| | 172 | | } |
| | 173 | | } |
| | 174 | | } |