classlib/ExpenseTracker.Infrastructure/DependencyInjection.cs
2024-08-07 21:12:02 +03:00

100 lines
3.5 KiB
C#

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using AspNetCore.Identity.Mongo;
using ExpenseTracker.Application.Common.Interfaces.Services;
using ExpenseTracker.Infrastructure.Identity.Models;
using ExpenseTracker.Infrastructure.Identity.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using ExpenseTracker.Infrastructure.Services;
using ExpenseTracker.Infrastructure.Email;
namespace ExpenseTracker.Infrastructure;
public static class DependencyInjection
{
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
services
.AddIdentity(configuration)
.AddAuthenticationWithJwt(configuration)
.AddServices();
return services;
}
private static IServiceCollection AddIdentity(this IServiceCollection services, IConfiguration configuration)
{
AddMongoDbIdentity();
return services;
void AddMongoDbIdentity()
{
var mongoDbConnectionString = $"{configuration["Database:ConnectionString"]}/{configuration["Database:IdentityPartitionName"]}";
services.AddIdentityMongoDbProvider<ApplicationUser, ApplicationRole, string>(
identity =>
{
},
mongo =>
{
mongo.ConnectionString = mongoDbConnectionString;
});
}
void AddPostgreSQLIdentity()
{
// TODO: Add PostgreSQL Identity connector
}
}
private static IServiceCollection AddAuthenticationWithJwt(this IServiceCollection services, IConfiguration configuration)
{
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.IncludeErrorDetails = true;
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidAudience = configuration["Jwt:Audience"],
ValidIssuer = configuration["Jwt:Issuer"],
ClockSkew = TimeSpan.Zero,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:IssuerSigningKey"]))
};
});
return services;
}
private static IServiceCollection AddServices(this IServiceCollection services)
{
services
.AddScoped<IAuthenticationService, AuthenticationService>()
.AddScoped<IEmailSenderService, EmailSenderService>()
.AddSingleton<ICurrencyConverterService, CurrencyConverterService>();
services.AddHttpClient(
"CurrencyConverterService",
client =>
{
client.BaseAddress = new Uri("https://api.freecurrencyapi.com/v1");
});
return services;
}
}