/
HomeController.cs
87 lines (74 loc) · 2.84 KB
/
HomeController.cs
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
using Microsoft.Azure.Management.Storage;
using Microsoft.Azure.Management.Storage.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult CreateAzureStorageAccount()
{
string resourceGroupName = "{your-resource-group-name}";
string token = GetAuthorizationHeader();
string subscriptionId = "{your-subscription-id}";
string stAccName = "brucestorage" + Guid.NewGuid().ToString().Substring(0, 8);
TokenCredentials tokenCredential = new TokenCredentials(token);
var storageManagementClient = new StorageManagementClient(tokenCredential);
storageManagementClient.SubscriptionId = subscriptionId;
var result = storageManagementClient.StorageAccounts.CreateAsync(resourceGroupName, stAccName,
new StorageAccountCreateParameters()
{
Kind = Kind.Storage,
Location = "West US",
Sku = new Sku(SkuName.StandardLRS)
}).Result;
return Json(result,JsonRequestBehavior.AllowGet);
}
private string GetAuthorizationHeader()
{
string tenantId = "{your-tenant-id}";
string clientId = "your-aad-app-client-id";
string clientSecrets = "{your-aad-app-client-secret}";
AuthenticationResult result = null;
var context = new AuthenticationContext(String.Format("https://login.windows.net/{0}", tenantId));
var thread = new Thread(() =>
{
var authParam = new PlatformParameters(PromptBehavior.Never, null);
result = context.AcquireTokenAsync(
"https://management.azure.com/"
, new ClientCredential(clientId, clientSecrets)
).Result;
});
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AquireTokenThread";
thread.Start();
thread.Join();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
}
}