forked from Azure/azure-storage-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AADAuthSamples.php
500 lines (437 loc) · 17.5 KB
/
AADAuthSamples.php
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
<?php
/**
* LICENSE: The MIT License (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* https://github.com/azure/azure-storage-php/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @category Microsoft
* @package MicrosoftAzure\Storage\Samples
* @author Azure Storage PHP SDK <[email protected]>
* @copyright 2019 Microsoft Corporation
* @license https://github.com/azure/azure-storage-php/LICENSE
* @link https://github.com/azure/azure-storage-php
*/
namespace MicrosoftAzure\Storage\Samples;
require_once "../vendor/autoload.php";
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Blob\BlobSharedAccessSignatureHelper;
use MicrosoftAzure\Storage\Blob\Models\CreateBlockBlobOptions;
use MicrosoftAzure\Storage\Blob\Models\CreateContainerOptions;
use MicrosoftAzure\Storage\Blob\Models\ListBlobsOptions;
use MicrosoftAzure\Storage\Blob\Models\PublicAccessType;
use MicrosoftAzure\Storage\Blob\Models\DeleteBlobOptions;
use MicrosoftAzure\Storage\Blob\Models\CreateBlobOptions;
use MicrosoftAzure\Storage\Blob\Models\GetBlobOptions;
use MicrosoftAzure\Storage\Blob\Models\SetBlobPropertiesOptions;
use MicrosoftAzure\Storage\Blob\Models\ListPageBlobRangesOptions;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Common\Exceptions\InvalidArgumentTypeException;
use MicrosoftAzure\Storage\Common\Internal\Resources;
use MicrosoftAzure\Storage\Common\Internal\StorageServiceSettings;
use MicrosoftAzure\Storage\Common\Models\Range;
use MicrosoftAzure\Storage\Common\Models\Logging;
use MicrosoftAzure\Storage\Common\Models\Metrics;
use MicrosoftAzure\Storage\Common\Models\RetentionPolicy;
use MicrosoftAzure\Storage\Common\Models\ServiceProperties;
$connectionString = 'DefaultEndpointsProtocol=https;AccountName=<YOUR_ACCOUNT_NAME>;';
$bearerToken = 'INITIAL BEARER TOKEN THAT DOES NOT WORK';
$blobClient = BlobRestProxy::createBlobServiceWithTokenCredential($bearerToken, $connectionString);
// to refresh token, simply modify it will change the value of the stored token.
$bearerToken = '<YOUR_BEARER_TOKEN>';
// A temporary container created and used through this sample, and finally deleted
$myContainer = 'mycontainer' . generateRandomString();
// Get and Set Blob Service Properties
setBlobServiceProperties($blobClient);
// To create a container call createContainer.
createContainerSample($blobClient);
// To get/set container properties
containerProperties($blobClient);
// To get/set container metadata
containerMetadata($blobClient);
// To upload a file as a blob, use the BlobRestProxy->createBlockBlob method. This operation will
// create the blob if it doesn't exist, or overwrite it if it does. The code example below assumes
// that the container has already been created and uses fopen to open the file as a stream.
uploadBlobSample($blobClient);
// To download blob into a file, use the BlobRestProxy->getBlob method. The example below assumes
// the blob to download has been already created.
downloadBlobSample($blobClient);
// To list the blobs in a container, use the BlobRestProxy->listBlobs method with a foreach loop to loop
// through the result. The following code outputs the name and URI of each blob in a container.
listBlobsSample($blobClient);
// To get set blob properties
blobProperties($blobClient);
// To get set blob metadata
blobMetadata($blobClient);
// Basic operations for page blob.
pageBlobOperations($blobClient);
// Snap shot operation for blob service.
snapshotOperations($blobClient);
// Basic lease operations.
leaseOperations($blobClient);
//Or to leverage the asynchronous methods provided, the operation can be done in
//a promise pipeline.
$containerName = '';
try {
$containerName = basicStorageBlobOperationAsync($blobClient)->wait();
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message.PHP_EOL;
} catch (InvalidArgumentTypeException $e) {
echo $e->getMessage().PHP_EOL;
}
try {
$blobClient->deleteContainerAsync($containerName)->wait();
cleanUp($blobClient);
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message.PHP_EOL;
}
function setBlobServiceProperties($blobClient)
{
// Get blob service properties
echo "Get Blob Service properties" . PHP_EOL;
$originalProperties = $blobClient->getServiceProperties();
// Set blob service properties
echo "Set Blob Service properties" . PHP_EOL;
$retentionPolicy = new RetentionPolicy();
$retentionPolicy->setEnabled(true);
$retentionPolicy->setDays(10);
$logging = new Logging();
$logging->setRetentionPolicy($retentionPolicy);
$logging->setVersion('1.0');
$logging->setDelete(true);
$logging->setRead(true);
$logging->setWrite(true);
$metrics = new Metrics();
$metrics->setRetentionPolicy($retentionPolicy);
$metrics->setVersion('1.0');
$metrics->setEnabled(true);
$metrics->setIncludeAPIs(true);
$serviceProperties = new ServiceProperties();
$serviceProperties->setLogging($logging);
$serviceProperties->setHourMetrics($metrics);
$blobClient->setServiceProperties($serviceProperties);
// revert back to original properties
echo "Revert back to original service properties" . PHP_EOL;
$blobClient->setServiceProperties($originalProperties->getValue());
echo "Service properties sample completed" . PHP_EOL;
}
function createContainerSample($blobClient)
{
// OPTIONAL: Set public access policy and metadata.
// Create container options object.
$createContainerOptions = new CreateContainerOptions();
// Set container metadata
$createContainerOptions->addMetaData("key1", "value1");
$createContainerOptions->addMetaData("key2", "value2");
try {
// Create container.
global $myContainer;
$blobClient->createContainer($myContainer, $createContainerOptions);
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message.PHP_EOL;
}
}
function containerProperties($blobClient)
{
$containerName = "mycontainer" . generateRandomString();
echo "Create container " . $containerName . PHP_EOL;
// Create container options object.
$createContainerOptions = new CreateContainerOptions();
// Set container metadata
$createContainerOptions->addMetaData("key1", "value1");
$createContainerOptions->addMetaData("key2", "value2");
// Create container.
$blobClient->createContainer($containerName, $createContainerOptions);
echo "Get container properties:" . PHP_EOL;
// Get container properties
$properties = $blobClient->getContainerProperties($containerName);
echo 'Last modified: ' . $properties->getLastModified()->format('Y-m-d H:i:s') . PHP_EOL;
echo 'ETAG: ' . $properties->getETag() . PHP_EOL;
echo "Delete container" . PHP_EOL;
$blobClient->deleteContainer($containerName) . PHP_EOL;
}
function containerMetadata($blobClient)
{
$containerName = "mycontainer" . generateRandomString();
echo "Create container " . $containerName . PHP_EOL;
// Create container options object.
$createContainerOptions = new CreateContainerOptions();
// Set container metadata
$createContainerOptions->addMetaData("key1", "value1");
$createContainerOptions->addMetaData("key2", "value2");
// Create container.
$blobClient->createContainer($containerName, $createContainerOptions);
echo "Get container metadata" . PHP_EOL;
// Get container properties
$properties = $blobClient->getContainerProperties($containerName);
foreach ($properties->getMetadata() as $key => $value) {
echo $key . ": " . $value . PHP_EOL;
}
echo "Delete container" . PHP_EOL;
$blobClient->deleteContainer($containerName);
}
function blobProperties($blobClient)
{
// Create container
$container = "mycontainer" . generateRandomString();
echo "Create container " . $container . PHP_EOL;
$blobClient->createContainer($container);
// Create blob
$blob = 'blob' . generateRandomString();
echo "Create blob " . PHP_EOL;
$blobClient->createPageBlob($container, $blob, 4096);
// Set blob properties
echo "Set blob properties" . PHP_EOL;
$opts = new SetBlobPropertiesOptions();
$opts->setCacheControl('test');
$opts->setContentEncoding('UTF-8');
$opts->setContentLanguage('en-us');
$opts->setContentLength(512);
$opts->setContentMD5(null);
$opts->setContentType('text/plain');
$opts->setSequenceNumberAction('increment');
$blobClient->setBlobProperties($container, $blob, $opts);
// Get blob properties
echo "Get blob properties" . PHP_EOL;
$result = $blobClient->getBlobProperties($container, $blob);
$props = $result->getProperties();
echo 'Cache control: ' . $props->getCacheControl() . PHP_EOL;
echo 'Content encoding: ' . $props->getContentEncoding() . PHP_EOL;
echo 'Content language: ' . $props->getContentLanguage() . PHP_EOL;
echo 'Content type: ' . $props->getContentType() . PHP_EOL;
echo 'Content length: ' . $props->getContentLength() . PHP_EOL;
echo 'Content MD5: ' . $props->getContentMD5() . PHP_EOL;
echo 'Last modified: ' . $props->getLastModified()->format('Y-m-d H:i:s') . PHP_EOL;
echo 'Blob type: ' . $props->getBlobType() . PHP_EOL;
echo 'Lease status: ' . $props->getLeaseStatus() . PHP_EOL;
echo 'Sequence number: ' . $props->getSequenceNumber() . PHP_EOL;
echo "Delete blob" . PHP_EOL;
$blobClient->deleteBlob($container, $blob);
echo "Delete container" . PHP_EOL;
$blobClient->deleteContainer($container);
}
function blobMetadata($blobClient)
{
// Create container
$container = "mycontainer" . generateRandomString();
echo "Create container " . $container . PHP_EOL;
$blobClient->createContainer($container);
// Create blob
$blob = 'blob' . generateRandomString();
echo "Create blob " . PHP_EOL;
$blobClient->createPageBlob($container, $blob, 4096);
// Set blob metadata
echo "Set blob metadata" . PHP_EOL;
$metadata = array(
'key' => 'value',
'foo' => 'bar',
'baz' => 'boo');
$blobClient->setBlobMetadata($container, $blob, $metadata);
// Get blob metadata
echo "Get blob metadata" . PHP_EOL;
$result = $blobClient->getBlobMetadata($container, $blob);
$retMetadata = $result->getMetadata();
foreach ($retMetadata as $key => $value) {
echo $key . ': ' . $value . PHP_EOL;
}
echo "Delete blob" . PHP_EOL;
$blobClient->deleteBlob($container, $blob);
echo "Delete container" . PHP_EOL;
$blobClient->deleteContainer($container);
}
function uploadBlobSample($blobClient)
{
if (!file_exists("myfile.txt")) {
$file = fopen("myfile.txt", 'w');
fwrite($file, 'Hello World!');
fclose($file);
}
$content = fopen("myfile.txt", "r");
$blob_name = "myblob";
$content2 = "string content";
$blob_name2 = "myblob2";
try {
//Upload blob
global $myContainer;
$blobClient->createBlockBlob($myContainer, $blob_name, $content);
$blobClient->createBlockBlob($myContainer, $blob_name2, $content2);
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message.PHP_EOL;
}
}
function downloadBlobSample($blobClient)
{
try {
global $myContainer;
$getBlobResult = $blobClient->getBlob($myContainer, "myblob");
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message.PHP_EOL;
}
file_put_contents("output.txt", $getBlobResult->getContentStream());
}
function listBlobsSample($blobClient)
{
try {
// List blobs.
$listBlobsOptions = new ListBlobsOptions();
$listBlobsOptions->setPrefix("myblob");
// Setting max result to 1 is just to demonstrate the continuation token.
// It is not the recommended value in a product environment.
$listBlobsOptions->setMaxResults(1);
do {
global $myContainer;
$blob_list = $blobClient->listBlobs($myContainer, $listBlobsOptions);
foreach ($blob_list->getBlobs() as $blob) {
echo $blob->getName().": ".$blob->getUrl().PHP_EOL;
}
$listBlobsOptions->setContinuationToken($blob_list->getContinuationToken());
} while ($blob_list->getContinuationToken());
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message.PHP_EOL;
}
}
function pageBlobOperations($blobClient)
{
global $myContainer;
$blobName = "HelloPageBlobWorld";
$containerName = $myContainer;
# Create a page blob
echo "Create Page Blob with name {$blobName}".PHP_EOL;
$blobClient->createPageBlob($containerName, $blobName, 2560);
# Create pages in a page blob
echo "Create pages in a page blob".PHP_EOL;
$blobClient->createBlobPages(
$containerName,
$blobName,
new Range(0, 511),
generateRandomString(512)
);
$blobClient->createBlobPages(
$containerName,
$blobName,
new Range(512, 1023),
generateRandomString(512)
);
# List page blob ranges
$listPageBlobRangesOptions = new ListPageBlobRangesOptions();
$listPageBlobRangesOptions->setRange(new Range(0, 1023));
echo "List Page Blob Ranges".PHP_EOL;
$listPageBlobRangesResult = $blobClient->listPageBlobRanges(
$containerName,
$blobName,
$listPageBlobRangesOptions
);
foreach ($listPageBlobRangesResult->getRanges() as $range) {
echo "Range:".$range->getStart()."-".$range->getEnd().PHP_EOL;
$getBlobOptions = new GetBlobOptions();
$getBlobOptions->setRange($range);
$getBlobResult = $blobClient->getBlob($containerName, $blobName, $getBlobOptions);
file_put_contents("PageContent.txt", $getBlobResult->getContentStream());
}
# Clean up after the sample
echo "Delete Blob".PHP_EOL;
$blobClient->deleteBlob($containerName, $blobName);
}
function snapshotOperations($blobClient)
{
global $myContainer;
$blobName = "HelloWorld";
$containerName = $myContainer;
# Upload file as a block blob
echo "Uploading BlockBlob".PHP_EOL;
$content = 'test content hello hello world';
$blobClient->createBlockBlob($containerName, $blobName, $content);
# Create a snapshot
echo "Create a Snapshot".PHP_EOL;
$snapshotResult = $blobClient->createBlobSnapshot($containerName, $blobName);
# Retrieve snapshot
echo "Retrieve Snapshot".PHP_EOL;
$getBlobOptions = new GetBlobOptions();
$getBlobOptions->setSnapshot($snapshotResult->getSnapshot());
$getBlobResult = $blobClient->getBlob($containerName, $blobName, $getBlobOptions);
file_put_contents("HelloWorldSnapshotCopy.png", $getBlobResult->getContentStream());
# Clean up after the sample
echo "Delete Blob and snapshot".PHP_EOL;
$deleteBlobOptions = new DeleteBlobOptions();
$deleteBlobOptions->setDeleteSnaphotsOnly(false);
$blobClient->deleteBlob($containerName, $blobName, $deleteBlobOptions);
}
function cleanUp($blobClient)
{
if (file_exists('output.txt')) {
unlink('output.txt');
}
if (file_exists('myfile.txt')) {
unlink('myfile.txt');
}
if (file_exists('outputBySAS.txt')) {
unlink('outputBySAS.txt');
}
if (file_exists('myblob.txt')) {
unlink('myblob.txt');
}
if (file_exists('PageContent.txt')) {
unlink('PageContent.txt');
}
if (file_exists('HelloWorldSnapshotCopy.png')) {
unlink('HelloWorldSnapshotCopy.png');
}
global $myContainer;
$blobClient->deleteContainer($myContainer);
echo "Successfully cleaned up\n";
}
function leaseOperations($blobClient)
{
// Create container
$container = "mycontainer" . generateRandomString();
echo "Create container " . $container . PHP_EOL;
$blobClient->createContainer($container);
// Create Blob
$blob = 'Blob' . generateRandomString();
echo "Create blob " . $blob . PHP_EOL;
$contentType = 'text/plain; charset=UTF-8';
$options = new CreateBlockBlobOptions();
$options->setContentType($contentType);
$blobClient->createBlockBlob($container, $blob, 'Hello world', $options);
// Acquire lease
$result = $blobClient->acquireLease($container, $blob);
try {
echo "Try delete blob without lease" . PHP_EOL;
$blobClient->deleteBlob($container, $blob);
} catch (ServiceException $e) {
echo "Delete blob with lease" . PHP_EOL;
$blobOptions = new DeleteBlobOptions();
$blobOptions->setLeaseId($result->getLeaseId());
$blobClient->deleteBlob($container, $blob, $blobOptions);
}
echo "Delete container" . PHP_EOL;
$blobClient->deleteContainer($container);
}
function generateRandomString($length = 6)
{
$characters = 'abcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}