1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
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<IAzure> AuthenticateOrGetAsync()
{
if (_credentials == null)
{
throw new NullReferenceException("Credentials were not set.");
}
if (_azure == null)
{
return Task.Factory.StartNew<IAzure>(() =>
{
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<IAzure> AuthenticateOrGetAsync(AzureUtilsCredentials credentials)
{
return Task.Factory.StartNew<IAzure>(() =>
{
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<IAzure> 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;
}
}
}
|