using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Tango.AzureUtils.Web; namespace Tango.AzureUtils { public class AzureUtilsAuthenticationFactory { private static IAzure _azure; private static AzureUtilsCredentials _credentials = new AzureUtilsCredentials() { ClientID = "be33437c-5052-449f-ab9d-a88d008eae24", ClientSecret = "Ontb_-o~T.2r.qO9xvZbSM_03k.6C47mM8", TenantID = "2ebd63a5-bc2f-41dc-9066-4409ed5e5dd4", SubscriptionID = "10c8aa60-3b15-4e0d-b412-6aeef90e5e91" }; public static void SetGlobalCredentials(AzureUtilsCredentials credentials) { _credentials = credentials; } public static Task AuthenticateOrGetAsync() { if (_credentials == null) { throw new NullReferenceException("Credentials were not set."); } if (_azure == null) { return Task.Factory.StartNew(() => { var creds = SdkContext.AzureCredentialsFactory.FromServicePrincipal( _credentials.ClientID, _credentials.ClientSecret, _credentials.TenantID, AzureEnvironment.AzureGlobalCloud); _azure = Azure.Authenticate(creds).WithSubscription(_credentials.SubscriptionID); return _azure; }); } else { return Task.FromResult(_azure); } } public static Task AuthenticateOrGetAsync(AzureUtilsCredentials credentials) { return Task.Factory.StartNew(() => { var creds = SdkContext.AzureCredentialsFactory.FromServicePrincipal( credentials.ClientID, credentials.ClientSecret, credentials.TenantID, AzureEnvironment.AzureGlobalCloud); _azure = Azure.Authenticate(creds).WithSubscription(credentials.SubscriptionID); return _azure; }); } public static async Task AuthenticateOrGetAsync(String gatewayUrl, String email, String password) { using (var http = new HttpClient()) { AzureUtilsWebClient client = new AzureUtilsWebClient(gatewayUrl, http); var response = await client.LoginAsync(new LoginRequest() { Email = email, Password = password }); http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", response.AccessToken); var c = await client.GetCredentialsAsync(); return await AuthenticateOrGetAsync(new AzureUtilsCredentials() { ClientID = c.ClientID, ClientSecret = c.ClientSecret, TenantID = c.TenantID, SubscriptionID = c.SubscriptionID }); } } public static AzureUtilsCredentials GetGlobalCredentials() { return _credentials; } } }