Add project files.

This commit is contained in:
Sergio Matias Urquin
2025-04-29 18:42:29 -06:00
parent 9c1958d351
commit 83fc1878c4
67 changed files with 4586 additions and 0 deletions

View File

@@ -0,0 +1,121 @@
using Azure.Core;
using Azure.Identity;
using MongoDB.Driver.Authentication.Oidc;
namespace Core.Blueprint.Mongo.Configuration
{
/// <summary>
/// The <see cref="HeathIdentityProvider"/> class is responsible for acquiring an OpenID Connect (OIDC)
/// access token for MongoDB authentication using Azure Identity and Managed Identity credentials.
/// </summary>
public class HeathIdentityProvider : IOidcCallback
{
/// <summary>
/// The audience (resource identifier) for which the OIDC token is being requested.
/// </summary>
private readonly string _audience;
/// <summary>
/// The environment in which the application is running (e.g., Development, Production).
/// </summary>
private readonly string _environment;
/// <summary>
/// Initializes a new instance of the <see cref="HeathIdentityProvider"/> class with the specified audience.
/// </summary>
/// <param name="audience">The audience (resource identifier) for which the OIDC token is being requested.</param>
public HeathIdentityProvider(string audience)
{
_audience = audience;
_environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;
}
/// <summary>
/// Synchronously retrieves the OIDC access token to authenticate to MongoDB.
/// </summary>
/// <param name="parameters">The callback parameters provided for the OIDC request.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <returns>An OIDC access token to authenticate to MongoDB.</returns>
/// <exception cref="Exception">Thrown if an error occurs during the token acquisition process.</exception>
public OidcAccessToken GetOidcAccessToken(OidcCallbackParameters parameters, CancellationToken cancellationToken)
{
try
{
AccessToken token;
TokenRequestContext tokenRequestContext =
new TokenRequestContext(
new[] { _audience }
);
if (_environment == "Local")
{
token =
new ChainedTokenCredential(
new ManagedIdentityCredential(),
new VisualStudioCredential(),
new VisualStudioCodeCredential(),
new SharedTokenCacheCredential()
)
.GetToken(tokenRequestContext);
}
else
{
token =
new ManagedIdentityCredential()
.GetToken(tokenRequestContext);
}
return new OidcAccessToken(token.Token, expiresIn: null);
}
catch (Exception ex)
{
throw new Exception($"An error occurred while trying to get the OIDC token to connect to the database, ERROR: {ex.Message}");
}
}
/// <summary>
/// Asynchronously retrieves the OIDC access token to authenticate to MongoDB.
/// </summary>
/// <param name="parameters">The callback parameters provided for the OIDC request.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <returns>A task that represents the asynchronous operation, with an OIDC access token as the result.</returns>
/// <exception cref="Exception">Thrown if an error occurs during the token acquisition process.</exception>
public async Task<OidcAccessToken> GetOidcAccessTokenAsync(OidcCallbackParameters parameters, CancellationToken cancellationToken)
{
try
{
TokenRequestContext tokenRequestContext =
new TokenRequestContext(
new[] { _audience }
);
AccessToken token;
if (_environment == "Local")
{
token = await new ChainedTokenCredential(
new ManagedIdentityCredential(),
new VisualStudioCredential(),
new VisualStudioCodeCredential(),
new SharedTokenCacheCredential()
)
.GetTokenAsync(tokenRequestContext, cancellationToken)
.ConfigureAwait(false);
}
else
{
token = await new ManagedIdentityCredential()
.GetTokenAsync(tokenRequestContext, cancellationToken)
.ConfigureAwait(false);
}
return new OidcAccessToken(token.Token, expiresIn: null);
}
catch (Exception ex)
{
throw new Exception($"An error occurred while trying to get the OIDC token to connect to the database, ERROR: {ex.Message}");
}
}
}
}

View File

@@ -0,0 +1,65 @@
using Core.Blueprint.Mongo;
using Core.Blueprint.Mongo.Configuration;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
namespace Core.Blueprint.DAL.Mongo.Configuration
{
/// <summary>
/// The <see cref="RegisterBlueprint"/> class contains extension methods for registering the MongoDB context and configuration settings
/// to the <see cref="IServiceCollection"/> in the dependency injection container.
/// </summary>
public static class RegisterBlueprint
{
/// <summary>
/// Adds the MongoDB layer services to the <see cref="IServiceCollection"/>.
/// Registers the MongoDB context and configuration settings for MongoDB connection, database name, and audience.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to which the services will be added.</param>
/// <param name="configuration">The <see cref="IConfiguration"/> used to load MongoDB settings.</param>
/// <returns>The updated <see cref="IServiceCollection"/> with MongoDB services registered.</returns>
public static IServiceCollection AddMongoLayer(this IServiceCollection services, IConfiguration configuration)
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;
services.AddSingleton<IMongoContext, MongoContext>();
var ConnectionString = configuration.GetSection("ConnectionStrings:MongoDB").Value ?? string.Empty;
var Databasename = configuration.GetSection("MongoDb:DatabaseName").Value ?? string.Empty;
var Audience = (environment == "Local")
? configuration.GetSection("MongoDb:LocalAudience").Value
: configuration.GetSection("MongoDb:Audience").Value;
if (string.IsNullOrEmpty(ConnectionString) || string.IsNullOrEmpty(Databasename) || string.IsNullOrEmpty(Audience))
throw new InvalidOperationException("Mongo connection is not configured correctly.");
services.Configure<MongoDbSettings>(options =>
{
options.ConnectionString = ConnectionString;
options.Databasename = Databasename;
options.Audience = Audience;
});
services.AddSingleton<IMongoClient>(serviceProvider =>
{
var settings = serviceProvider.GetRequiredService<IOptions<MongoDbSettings>>().Value;
var mongoClientSettings = MongoClientSettings.FromConnectionString(settings.ConnectionString);
mongoClientSettings.Credential = MongoCredential.CreateOidcCredential(new HeathIdentityProvider(settings.Audience));
return new MongoClient(mongoClientSettings);
});
services.AddSingleton<IMongoDatabase>(serviceProvider =>
{
var settings = serviceProvider.GetRequiredService<IOptions<MongoDbSettings>>().Value;
var client = serviceProvider.GetRequiredService<IMongoClient>();
return client.GetDatabase(settings.Databasename);
});
services.AddSingleton<IMongoDbSettings>(serviceProvider => serviceProvider.GetRequiredService<IOptions<MongoDbSettings>>().Value);
return services;
}
}
}