-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathProgram.cs
213 lines (196 loc) · 9.86 KB
/
Program.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.Graph.RBAC.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Samples.Common;
using System;
using System.IO;
using System.Linq;
namespace ManageServicePrincipal
{
public class Program
{
public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var authenticated = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials);
RunSample(authenticated);
Console.ReadLine();
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
/**
* Azure Service Principal sample for managing Service Principal -
* - Create an Active Directory application
* - Create a Service Principal for the application and assign a role
* - Export the Service Principal to an authentication file
* - Use the file to list subcription virtual machines
* - Update the application
* - Update the service principal to revoke the password credential and the role
* - Delete the Service Principal.
*/
public static void RunSample(Azure.IAuthenticated authenticated)
{
string subscriptionId = authenticated.Subscriptions.List().First<ISubscription>().SubscriptionId;
Utilities.Log("Selected subscription: " + subscriptionId);
IActiveDirectoryApplication activeDirectoryApplication = null;
string authFilePath = Path.Combine(Utilities.ProjectPath, "Asset", "mySamplAuthdFile.azureauth").ToString();
try
{
activeDirectoryApplication = CreateActiveDirectoryApplication(authenticated);
IServicePrincipal servicePrincipal = CreateServicePrincipalWithRoleForApplicationAndExportToFile(authenticated, activeDirectoryApplication, BuiltInRole.Contributor, subscriptionId, authFilePath);
// Wait until Service Principal is ready
SdkContext.DelayProvider.Delay(15);
UseAuthFile(authFilePath);
UpdateApplication(authenticated, activeDirectoryApplication);
UpdateServicePrincipal(authenticated, servicePrincipal);
}
finally
{
Utilities.Log("Deleting Active Directory application and Service Principal...");
if (activeDirectoryApplication != null)
{
// this will delete Service Principal as well
authenticated.ActiveDirectoryApplications.DeleteById(activeDirectoryApplication.Id);
}
}
}
private static IActiveDirectoryApplication CreateActiveDirectoryApplication(Azure.IAuthenticated authenticated)
{
Utilities.Log("Creating Active Directory application...");
var name = SdkContext.RandomResourceName("adapp-sample", 20);
//create a self-sighed certificate
var domainName = name + ".com";
var certPassword = Utilities.CreatePassword();
Certificate certificate = Certificate.CreateSelfSigned(domainName, certPassword);
// create Active Directory application
var activeDirectoryApplication = authenticated.ActiveDirectoryApplications
.Define(name)
.WithSignOnUrl("https://github.com/Azure/azure-sdk-for-java/" + name)
// password credentials definition
.DefinePasswordCredential("password")
.WithPasswordValue("P@ssw0rd")
.WithDuration(TimeSpan.FromDays(700))
.Attach()
// certificate credentials definition
.DefineCertificateCredential("cert")
.WithAsymmetricX509Certificate()
.WithPublicKey(File.ReadAllBytes(certificate.CerPath))
.WithDuration(TimeSpan.FromDays(100))
.Attach()
.Create();
Utilities.Log(activeDirectoryApplication.Id + " - " + activeDirectoryApplication.ApplicationId);
return activeDirectoryApplication;
}
private static IServicePrincipal CreateServicePrincipalWithRoleForApplicationAndExportToFile (
Azure.IAuthenticated authenticated,
IActiveDirectoryApplication activeDirectoryApplication,
BuiltInRole role,
string subscriptionId,
string authFilePath)
{
Utilities.Log("Creating Service Principal...");
string name = SdkContext.RandomResourceName("sp-sample", 20);
//create a self-sighed certificate
string domainName = name + ".com";
string certPassword = Utilities.CreatePassword();
Certificate certificate = Certificate.CreateSelfSigned(domainName, certPassword);
// create a Service Principal and assign it to a subscription with the role Contributor
return authenticated.ServicePrincipals
.Define("name")
.WithExistingApplication(activeDirectoryApplication)
// password credentials definition
.DefinePasswordCredential("ServicePrincipalAzureSample")
.WithPasswordValue(Utilities.CreatePassword())
.Attach()
// certificate credentials definition
.DefineCertificateCredential("spcert")
.WithAsymmetricX509Certificate()
.WithPublicKey(File.ReadAllBytes(certificate.CerPath))
.WithDuration(TimeSpan.FromDays(7))
// export the credentials to the file
.WithAuthFileToExport(new StreamWriter(new FileStream(authFilePath, FileMode.OpenOrCreate)))
.WithPrivateKeyFile(certificate.PfxPath)
.WithPrivateKeyPassword(certPassword)
.Attach()
.WithNewRoleInSubscription(role, subscriptionId)
.Create();
}
private static void UseAuthFile(string authFilePath)
{
Utilities.Log("Using auth file to list virtual machines...");
// use just created auth file to sign in.
var azure = Azure.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(SdkContext.AzureCredentialsFactory.FromFile(authFilePath))
.WithDefaultSubscription();
// list virtualMachines, if any.
var vmList = azure.VirtualMachines.List();
foreach (var vm in vmList)
{
Utilities.PrintVirtualMachine(vm);
}
}
private static void UpdateApplication(Azure.IAuthenticated authenticated, IActiveDirectoryApplication activeDirectoryApplication)
{
Utilities.Log("Updating Active Directory application...");
activeDirectoryApplication.Update()
// add another password credentials
.DefinePasswordCredential("password-1")
.WithPasswordValue("P@ssw0rd-1")
.WithDuration(TimeSpan.FromDays(700))
.Attach()
// add a reply url
.WithReplyUrl("http://localhost:8080")
.Apply();
}
private static void UpdateServicePrincipal(Azure.IAuthenticated authenticated, IServicePrincipal servicePrincipal)
{
Utilities.Log("Updating Service Principal...");
servicePrincipal.Update()
// add another password credentials
.WithoutCredential("ServicePrincipalAzureSample")
.WithoutRole(servicePrincipal.RoleAssignments.First())
.Apply();
}
private class Certificate
{
public string PfxPath
{
get;
private set;
}
public string CerPath
{
get;
private set;
}
public static Certificate CreateSelfSigned(string domainName, string password)
{
return new Certificate(domainName, password);
}
private Certificate(string domainName, string password)
{
string pfxName = domainName + ".pfx";
string cerName = domainName + ".cer";
PfxPath = Path.Combine(Utilities.ProjectPath, "Asset", pfxName);
CerPath = Path.Combine(Utilities.ProjectPath, "Asset", cerName);
Utilities.Log("Creating a self-signed certificate " + pfxName + " ...");
Utilities.CreateCertificate(domainName, pfxName, cerName, password);
}
}
}
}