-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathManageServicePrincipal.java
237 lines (205 loc) · 10.3 KB
/
ManageServicePrincipal.java
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.graphrbac.samples;
import com.microsoft.azure.management.Azure;
import com.microsoft.azure.management.compute.VirtualMachine;
import com.microsoft.azure.management.graphrbac.ActiveDirectoryApplication;
import com.microsoft.azure.management.graphrbac.BuiltInRole;
import com.microsoft.azure.management.graphrbac.ServicePrincipal;
import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext;
import com.microsoft.azure.management.samples.Utils;
import com.microsoft.rest.LogLevel;
import org.joda.time.Duration;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
/**
* 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 application and Service Principal.
*/
public final class ManageServicePrincipal {
/**
* Main entry point.
* @param args the parameters
*/
public static void main(String[] args) {
try {
final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));
Azure.Authenticated authenticated = Azure.configure()
.withLogLevel(LogLevel.BODY)
.authenticate(credFile);
String defaultSubscriptionId = authenticated.subscriptions().list().get(0).subscriptionId();
runSample(authenticated, defaultSubscriptionId);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
/**
* Main function which runs the actual sample.
* @param authenticated instance of Authenticated
* @param defaultSubscriptionId default subscription id
* @return true if sample runs successfully
*/
public static boolean runSample(Azure.Authenticated authenticated, String defaultSubscriptionId) {
ActiveDirectoryApplication activeDirectoryApplication = null;
try {
String authFileName = "myAuthFile.azureauth";
String authFilePath = Paths.get(getBasePath(), authFileName).toString();
activeDirectoryApplication =
createActiveDirectoryApplication(authenticated);
ServicePrincipal servicePrincipal =
createServicePrincipalWithRoleForApplicationAndExportToFile(
authenticated,
activeDirectoryApplication,
BuiltInRole.CONTRIBUTOR,
defaultSubscriptionId,
authFilePath);
SdkContext.sleep(15000);
useAuthFile(authFilePath);
manageApplication(authenticated, activeDirectoryApplication);
manageServicePrincipal(authenticated, servicePrincipal);
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
if (activeDirectoryApplication != null) {
// this will delete Service Principal as well
authenticated.activeDirectoryApplications().deleteById(activeDirectoryApplication.id());
}
}
return false;
}
private static ActiveDirectoryApplication createActiveDirectoryApplication(Azure.Authenticated authenticated) throws Exception {
String name = SdkContext.randomResourceName("adapp-sample", 20);
//create a self-sighed certificate
String domainName = name + ".com";
// [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")]
String certPassword = "StrongPass!12";
Certificate certificate = Certificate.createSelfSigned(domainName, certPassword);
// create Active Directory application
ActiveDirectoryApplication activeDirectoryApplication = authenticated.activeDirectoryApplications()
.define(name)
.withSignOnUrl("https://github.com/Azure/azure-sdk-for-java/" + name)
// password credentials definition
.definePasswordCredential("password")
// [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")]
.withPasswordValue("P@ssw0rd")
.withDuration(Duration.standardDays(700))
.attach()
// certificate credentials definition
.defineCertificateCredential("cert")
.withAsymmetricX509Certificate()
.withPublicKey(Files.readAllBytes(Paths.get(certificate.getCerPath())))
.withDuration(Duration.standardDays(100))
.attach()
.create();
System.out.println(activeDirectoryApplication.id() + " - " + activeDirectoryApplication.applicationId());
return activeDirectoryApplication;
}
private static ServicePrincipal createServicePrincipalWithRoleForApplicationAndExportToFile(
Azure.Authenticated authenticated,
ActiveDirectoryApplication activeDirectoryApplication,
BuiltInRole role,
String subscriptionId,
String authFilePath) throws Exception {
String name = SdkContext.randomResourceName("sp-sample", 20);
//create a self-sighed certificate
String domainName = name + ".com";
// [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")]
String certPassword = "StrongPass!12";
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")
// [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")]
.withPasswordValue("StrongPass!12")
.attach()
// certificate credentials definition
.defineCertificateCredential("spcert")
.withAsymmetricX509Certificate()
.withPublicKey(Files.readAllBytes(Paths.get(certificate.getCerPath())))
.withDuration(Duration.standardDays(7))
// export the credentials to the file
.withAuthFileToExport(new FileOutputStream(authFilePath))
.withPrivateKeyFile(certificate.getPfxPath())
.withPrivateKeyPassword(certPassword)
.attach()
.withNewRoleInSubscription(role, subscriptionId)
.create();
}
private static void useAuthFile(String authFilePath) throws IOException {
// use just created auth file to sign in.
Azure azure = Azure.configure()
.withLogLevel(LogLevel.BODY)
.authenticate(new File(authFilePath))
.withDefaultSubscription();
// list virtualMachines, if any.
List<VirtualMachine> resourceGroups = azure.virtualMachines().list();
for (VirtualMachine vm : resourceGroups) {
Utils.print(vm);
}
}
private static void manageApplication(Azure.Authenticated authenticated, ActiveDirectoryApplication activeDirectoryApplication) {
activeDirectoryApplication.update()
// add another password credentials
.definePasswordCredential("password-1")
.withPasswordValue("P@ssw0rd-1")
.withDuration(Duration.standardDays(700))
.attach()
// add a reply url
.withReplyUrl("http://localhost:8080")
.apply();
}
private static void manageServicePrincipal(Azure.Authenticated authenticated, ServicePrincipal servicePrincipal) {
servicePrincipal.update()
.withoutCredential("ServicePrincipalAzureSample")
.withoutRole(servicePrincipal.roleAssignments().iterator().next())
.apply();
}
private ManageServicePrincipal() {
}
private static String basePath = null;
private static String getBasePath() throws URISyntaxException {
if (basePath == null) {
basePath = Paths.get(ManageServicePrincipal.class.getResource("/").toURI()).toString();
}
return basePath;
}
private static final class Certificate {
String pfxPath;
String cerPath;
public static Certificate createSelfSigned(String domainName, String password) throws Exception {
return new Certificate(domainName, password);
}
public String getPfxPath() {
return pfxPath;
}
public String getCerPath() {
return cerPath;
}
private Certificate(String domainName, String password) throws Exception {
pfxPath = Paths.get(getBasePath(), domainName + ".pfx").toString();
cerPath = Paths.get(getBasePath(), domainName + ".cer").toString();
System.out.println("Creating a self-signed certificate " + pfxPath + "...");
Utils.createCertificate(cerPath, pfxPath, domainName, password, "*." + domainName);
}
}
}