| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using Azure.Core; |
| | 6 | |
|
| | 7 | | namespace Azure.Iot.Hub.Service.Authentication |
| | 8 | | { |
| | 9 | | /// <summary> |
| | 10 | | /// The IoT Hub credentials, to be used for authenticating against an IoT Hub instance via SAS tokens. |
| | 11 | | /// </summary> |
| | 12 | | public class IotHubSasCredential : ISasTokenProvider |
| | 13 | | { |
| | 14 | | // Time buffer before expiry when the token should be renewed, expressed as a percentage of the time to live. |
| | 15 | | // The token will be renewed when it has 15% or less of the sas token's lifespan left. |
| | 16 | | private const int RenewalTimeBufferPercentage = 15; |
| | 17 | |
|
| 88 | 18 | | private readonly object _lock = new object(); |
| | 19 | |
|
| | 20 | | private string _cachedSasToken; |
| | 21 | | private DateTimeOffset _tokenExpiryTime; |
| | 22 | |
|
| 76 | 23 | | internal IotHubSasCredential(string connectionString) |
| | 24 | | { |
| 76 | 25 | | Argument.AssertNotNullOrWhiteSpace(connectionString, nameof(connectionString)); |
| | 26 | |
|
| 76 | 27 | | var iotHubConnectionString = ConnectionString.Parse(connectionString); |
| | 28 | |
|
| 76 | 29 | | var sharedAccessPolicy = iotHubConnectionString.GetRequired(SharedAccessSignatureConstants.SharedAccessPolic |
| 76 | 30 | | var sharedAccessKey = iotHubConnectionString.GetRequired(SharedAccessSignatureConstants.SharedAccessKeyIdent |
| | 31 | |
|
| 76 | 32 | | Endpoint = BuildEndpointUriFromHostName(iotHubConnectionString.GetRequired(SharedAccessSignatureConstants.Ho |
| 76 | 33 | | SetCredentials(sharedAccessPolicy, sharedAccessKey); |
| 76 | 34 | | } |
| | 35 | |
|
| | 36 | | /// <summary> |
| | 37 | | /// Initializes a new instance of <see cref="IotHubSasCredential"/> class. |
| | 38 | | /// </summary> |
| | 39 | | /// <param name="sharedAccessPolicy"> |
| | 40 | | /// The IoT Hub access permission, which can be either "iothubowner", "service", "registryRead" or "registryRead |
| | 41 | | /// For more information, see <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-securit |
| | 42 | | /// </param> |
| | 43 | | /// <param name="sharedAccessKey"> |
| | 44 | | /// The IoT Hub shared access key associated with the shared access policy permissions. |
| | 45 | | /// </param> |
| | 46 | | /// <param name="timeToLive"> |
| | 47 | | /// (Optional) The validity duration of the generated shared access signature token used for authentication. |
| | 48 | | /// The token will be renewed when at 15% or less of it's lifespan. The default value is 30 minutes. |
| | 49 | | /// </param> |
| 12 | 50 | | public IotHubSasCredential(string sharedAccessPolicy, string sharedAccessKey, TimeSpan timeToLive = default) |
| | 51 | | { |
| 12 | 52 | | Argument.AssertNotNullOrWhiteSpace(sharedAccessPolicy, nameof(sharedAccessPolicy)); |
| 10 | 53 | | Argument.AssertNotNullOrWhiteSpace(sharedAccessKey, nameof(sharedAccessKey)); |
| | 54 | |
|
| 8 | 55 | | SetCredentials(sharedAccessPolicy, sharedAccessKey, timeToLive); |
| 6 | 56 | | } |
| | 57 | |
|
| | 58 | | private void SetCredentials(string sharedAccessPolicy, string sharedAccessKey, TimeSpan timeToLive = default) |
| | 59 | | { |
| 84 | 60 | | SharedAccessPolicy = sharedAccessPolicy; |
| 84 | 61 | | SharedAccessKey = sharedAccessKey; |
| | 62 | |
|
| 84 | 63 | | if (!timeToLive.Equals(TimeSpan.Zero)) |
| | 64 | | { |
| 6 | 65 | | if (timeToLive.CompareTo(TimeSpan.Zero) < 0) |
| | 66 | | { |
| 2 | 67 | | throw new ArgumentException("The value for SasTokenTimeToLive cannot be a negative TimeSpan", nameof |
| | 68 | | } |
| | 69 | |
|
| 4 | 70 | | SasTokenTimeToLive = timeToLive; |
| | 71 | | } |
| | 72 | |
|
| 82 | 73 | | _cachedSasToken = null; |
| 82 | 74 | | } |
| | 75 | |
|
| | 76 | | /// <summary> |
| | 77 | | /// The IoT Hub service instance endpoint to connect to. |
| | 78 | | /// </summary> |
| 466 | 79 | | public Uri Endpoint { get; internal set; } |
| | 80 | |
|
| | 81 | | /// <summary> |
| | 82 | | /// The IoT Hub access permission, which can be either "iothubowner", "service", "registryRead" or "registryRead |
| | 83 | | /// For more information, see <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-securit |
| | 84 | | /// </summary> |
| 166 | 85 | | public string SharedAccessPolicy { get; private set; } |
| | 86 | |
|
| | 87 | | /// <summary> |
| | 88 | | /// The IoT Hub shared access key associated with the shared access policy permissions. |
| | 89 | | /// </summary> |
| 166 | 90 | | public string SharedAccessKey { get; private set; } |
| | 91 | |
|
| | 92 | | /// <summary> |
| | 93 | | /// The validity duration of the generated shared access signature token used for authentication. |
| | 94 | | /// The token will be renewed when at 15% or less of its lifespan. The default value is 30 minutes. |
| | 95 | | /// </summary> |
| 576 | 96 | | public TimeSpan SasTokenTimeToLive { get; private set; } = TimeSpan.FromMinutes(30); |
| | 97 | |
|
| | 98 | | private static Uri BuildEndpointUriFromHostName(string hostName) |
| | 99 | | { |
| 76 | 100 | | return new UriBuilder |
| 76 | 101 | | { |
| 76 | 102 | | Scheme = Uri.UriSchemeHttps, |
| 76 | 103 | | Host = hostName |
| 76 | 104 | | }.Uri; |
| | 105 | | } |
| | 106 | |
|
| | 107 | | public string GetSasToken() |
| | 108 | | { |
| 398 | 109 | | lock (_lock) |
| | 110 | | { |
| 398 | 111 | | if (TokenShouldBeGenerated()) |
| | 112 | | { |
| 82 | 113 | | var builder = new SharedAccessSignatureBuilder |
| 82 | 114 | | { |
| 82 | 115 | | HostName = Endpoint.Host, |
| 82 | 116 | | SharedAccessPolicy = SharedAccessPolicy, |
| 82 | 117 | | SharedAccessKey = SharedAccessKey, |
| 82 | 118 | | TimeToLive = SasTokenTimeToLive, |
| 82 | 119 | | }; |
| | 120 | |
|
| 82 | 121 | | _tokenExpiryTime = DateTimeOffset.UtcNow.Add(SasTokenTimeToLive); |
| 82 | 122 | | _cachedSasToken = builder.ToSignature(); |
| | 123 | | } |
| | 124 | |
|
| 398 | 125 | | return _cachedSasToken; |
| | 126 | | } |
| 398 | 127 | | } |
| | 128 | |
|
| | 129 | | private bool TokenShouldBeGenerated() |
| | 130 | | { |
| | 131 | | // The token needs to be generated if this is the first time it is being accessed (not cached yet) |
| | 132 | | // or the current time is greater than or equal to the token expiry time, less 15% buffer. |
| 398 | 133 | | if (_cachedSasToken == null) |
| | 134 | | { |
| 80 | 135 | | return true; |
| | 136 | | } |
| | 137 | |
|
| 318 | 138 | | var bufferTimeInMilliseconds = (double)RenewalTimeBufferPercentage / 100 * SasTokenTimeToLive.TotalMilliseco |
| 318 | 139 | | DateTimeOffset tokenExpiryTimeWithBuffer = _tokenExpiryTime.AddMilliseconds(-bufferTimeInMilliseconds); |
| 318 | 140 | | return DateTimeOffset.UtcNow.CompareTo(tokenExpiryTimeWithBuffer) >= 0; |
| | 141 | | } |
| | 142 | | } |
| | 143 | | } |