MireaBackend/Security/DependencyInjection.cs

69 lines
2.8 KiB
C#
Raw Normal View History

2024-05-29 04:09:10 +03:00
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
2024-11-04 02:39:10 +03:00
using Mirea.Api.Security.Common.Domain;
2024-05-29 04:34:00 +03:00
using Mirea.Api.Security.Common.Interfaces;
2024-05-29 04:11:04 +03:00
using Mirea.Api.Security.Services;
2024-05-29 04:34:00 +03:00
using System;
2024-11-04 02:39:10 +03:00
using System.Collections.Generic;
2024-05-29 04:09:10 +03:00
namespace Mirea.Api.Security;
public static class DependencyInjection
{
2024-05-29 04:11:04 +03:00
public static IServiceCollection AddSecurityServices(this IServiceCollection services, IConfiguration configuration)
2024-05-29 04:09:10 +03:00
{
var saltSize = int.Parse(configuration["SECURITY_SALT_SIZE"]!);
var hashSize = int.Parse(configuration["SECURITY_HASH_SIZE"]!);
var iteration = int.Parse(configuration["SECURITY_HASH_ITERATION"]!);
var memory = int.Parse(configuration["SECURITY_HASH_MEMORY"]!);
var parallelism = int.Parse(configuration["SECURITY_HASH_PARALLELISM"]!);
services.AddSingleton(new PasswordHashService
{
SaltSize = saltSize,
HashSize = hashSize,
Iterations = iteration,
Memory = memory,
Parallelism = parallelism,
Secret = configuration["SECURITY_HASH_TOKEN"]
});
2024-05-29 06:04:09 +03:00
var lifeTimeRefreshToken = TimeSpan.FromMinutes(int.Parse(configuration["SECURITY_LIFE_TIME_RT"]!));
var lifeTimeFirstAuthToken = TimeSpan.FromMinutes(int.Parse(configuration["SECURITY_LIFE_TIME_1_FA"]!));
2024-05-29 06:04:09 +03:00
services.AddSingleton(provider =>
{
var cacheService = provider.GetRequiredService<ICacheService>();
var accessTokenService = provider.GetRequiredService<IAccessToken>();
var revokedTokenService = provider.GetRequiredService<IRevokedToken>();
var logger = provider.GetRequiredService<ILogger<AuthService>>();
var passwordService = provider.GetRequiredService<PasswordHashService>();
2024-05-29 06:04:09 +03:00
return new AuthService(cacheService, accessTokenService, revokedTokenService, logger, passwordService)
2024-05-29 06:04:09 +03:00
{
Lifetime = lifeTimeRefreshToken,
LifetimeFirstAuth = lifeTimeFirstAuthToken
2024-05-29 04:34:00 +03:00
};
});
2024-11-04 02:39:10 +03:00
var providers = new Dictionary<OAuthProvider, (string ClientId, string Secret)>();
foreach (var provider in Enum.GetValues<OAuthProvider>())
{
var providerName = Enum.GetName(provider)!.ToUpper();
var clientId = configuration[$"{providerName}_CLIENT_ID"];
var secret = configuration[$"{providerName}_CLIENT_SECRET"];
if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(secret))
continue;
providers.Add(provider, (clientId, secret));
}
services.AddSingleton(provider => new OAuthService(provider.GetRequiredService<ILogger<OAuthService>>(), providers,
configuration["SECURITY_ENCRYPTION_TOKEN"]!));
2024-11-04 02:39:10 +03:00
2024-05-29 04:09:10 +03:00
return services;
}
}