umbraco / Umbraco.StorageProviders

MIT License
29 stars 21 forks source link

Support for managed identities #21

Closed lumimario closed 2 years ago

lumimario commented 3 years ago

It would be great if this provider supported Managed Identities:

ronaldbarendse commented 2 years ago

Adding support for managed identities would require taking a dependency on Azure.Identity to pass in the DefaultAzureCredential into the BlobContainerClient constructor.

I've updated the constructors of AzureBlobFileSystem and AzureBlobFileSystemImageCache to allow passing in a BlobContainerClient in PR https://github.com/umbraco/Umbraco.StorageProviders/pull/36, so that would allow you to manually configure the media file system and ImageSharp cache using:

public static IUmbracoBuilder AddAzureBlobMediaFileSystem(this IUmbracoBuilder builder, Uri blobContainerUri, bool useAzureBlobImageCache = true)
{
    if (builder == null) throw new ArgumentNullException(nameof(builder));

    builder.SetMediaFileSystem(provider =>
    {
        var globalSettingsOptions = provider.GetRequiredService<IOptions<GlobalSettings>>();
        var hostingEnvironment = provider.GetRequiredService<IHostingEnvironment>();

        var rootUrl = hostingEnvironment.ToAbsolute(globalSettingsOptions.Value.UmbracoMediaPath);
        var blobContainerClient = new BlobContainerClient(blobContainerUri, new DefaultAzureCredential());
        var ioHelper = provider.GetRequiredService<IOHelper>();
        var contentTypeProvider = provider.GetRequiredService<IContentTypeProvider>();

        return new AzureBlobFileSystem(rootUrl, blobContainerClient, ioHelper, contentTypeProvider);
    });

    // ImageSharp image cache
    if (useAzureBlobImageCache)
    {
        builder.Services.AddUnique<IImageCache>(_ =>
        {
            var blobContainerClient = new BlobContainerClient(blobContainerUri, new DefaultAzureCredential());

            return new AzureBlobFileSystemImageCache(blobContainerClient);
        });
    }

    return builder;
}

The above code won't get shipped as part of this package, because of the required dependency on Azure.Identity and probably also not as an add-on package within this repository, because it's not using any of the existing options/configuration and not using the IAzureBlobFileSystemProvider. I think that's fine trade-off though, as the above code is simple enough to manage yourself (besides, the credentials are already managed for you 😉)...