public async Task <string> GetModulePrimaryKey(RequestedResource sr) { var credentials = SdkContext.AzureCredentialsFactory.FromMSI(new MSILoginInformation(MSIResourceType.AppService), AzureEnvironment.AzureGlobalCloud); var azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithDefaultSubscription(); string iothubowner = string.Empty; var azureServiceTokenProvider = new AzureServiceTokenProvider(); string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com"); IotHubClient hubClient = new IotHubClient(new TokenCredentials(accessToken)) { SubscriptionId = azure.GetCurrentSubscription().SubscriptionId }; var listHubs = await hubClient.IotHubResource.ListBySubscriptionAsync(); do { var hub = listHubs.Where(iothub => string.Equals(iothub.Name, sr.iotHubName)).FirstOrDefault(); if (!string.IsNullOrEmpty(hub.Id)) { iothubowner = (await hubClient.IotHubResource.GetKeysForKeyNameAsync(GetResourceGroupName(hub.Id), hub.Name, "iothubowner")).PrimaryKey; break; } } while (!string.IsNullOrEmpty(listHubs.NextPageLink)); if (string.IsNullOrEmpty(iothubowner)) { throw new Exception("Failed to retrieve IoT Hub Primary Key string"); } string iotHubConnString = IotHubConnectionStringBuilder.Create(sr.iotHubFQDN, new ServiceAuthenticationWithSharedAccessPolicyKey("iothubowner", iothubowner)).ToString(); RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnString); var modulesOnDevice = await registryManager.GetModuleAsync(sr.deviceId, sr.moduleId); return(!string.IsNullOrEmpty(modulesOnDevice.Authentication.SymmetricKey.PrimaryKey) ? modulesOnDevice.Authentication.SymmetricKey.PrimaryKey : null); }
public AuthorizationHeaderHandler(string receivedHeader) { try { receivedHeader = System.Net.WebUtility.UrlDecode(receivedHeader); IDictionary <string, string> parsedFields = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); string[] fields = receivedHeader.Replace("SharedAccessSignature ", "").Trim().Split("&", StringSplitOptions.None); foreach (string field in fields) { if (field != string.Empty) { string[] fieldParts = field.Split("=", StringSplitOptions.None); if (fieldParts[0].Equals("sig")) { //Replace switched characters and properly pad the base64 signature fieldParts[1] = fieldParts[1].Replace('-', '+').Replace('_', '/'); if (fieldParts[1].Length % 4 == 2) { fieldParts[1] += "=="; } else if (fieldParts[1].Length % 4 == 3) { fieldParts[1] += "="; } } parsedFields.Add(fieldParts[0], fieldParts[1]); } } requestedResource = new RequestedResource(parsedFields["sr"]); expiry = parsedFields["se"]; signature = parsedFields["sig"]; } catch (Exception) { throw new Exception("Invalid header received"); } }