From b84dd47fee90a5188f0c5d4bf2f5bf90f37e6571 Mon Sep 17 00:00:00 2001 From: amiralirahimii Date: Wed, 4 Sep 2024 15:43:18 +0330 Subject: [PATCH 1/2] refactor: move sensitive data to .env file --- .gitignore | 7 +++++++ src/Web/Program.cs | 10 ++++++---- src/Web/Services/TokenService.cs | 11 +++++------ src/Web/Startup/SeedData.cs | 16 +++++++--------- src/Web/Startup/ServiceExtensions.Auth.cs | 12 ++++++++---- src/Web/Startup/ServiceExtensions.Cors.cs | 9 ++++----- src/Web/Startup/ServiceExtensions.Infra.cs | 8 ++++++-- src/Web/Web.csproj | 1 + src/Web/appsettings.json | 20 ++++++-------------- 9 files changed, 50 insertions(+), 44 deletions(-) diff --git a/.gitignore b/.gitignore index 006474c..67bf95d 100644 --- a/.gitignore +++ b/.gitignore @@ -624,6 +624,13 @@ fabric.properties .history .ionide +### ignore environment ### +.env +.env.local +.env.development +.env.test +.env.production + ### VisualStudio ### # User-specific files diff --git a/src/Web/Program.cs b/src/Web/Program.cs index 15e3684..4ef7ddb 100644 --- a/src/Web/Program.cs +++ b/src/Web/Program.cs @@ -1,6 +1,8 @@ using Web.Startup; +using DotNetEnv; var builder = WebApplication.CreateBuilder(args); +Env.Load(); var config = builder.Configuration; @@ -9,11 +11,11 @@ { options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }); -builder.Services.AddInfrastructureServices(config); -builder.Services.ConfigureAppAuthenticationServices(config); +builder.Services.AddInfrastructureServices(); +builder.Services.ConfigureAppAuthenticationServices(); builder.Services.AddApplicationServices(); builder.Services.AddSwaggerDocumentation(); -builder.Services.AddCorsPolicy(); +builder.Services.AddCorsPolicy(config); var app = builder.Build(); @@ -23,6 +25,6 @@ using (var scope = app.Services.CreateScope()) { var services = scope.ServiceProvider; - await SeedData.Initialize(services, config); + await SeedData.Initialize(services); } app.Run(); \ No newline at end of file diff --git a/src/Web/Services/TokenService.cs b/src/Web/Services/TokenService.cs index 1134a4c..1a24f63 100644 --- a/src/Web/Services/TokenService.cs +++ b/src/Web/Services/TokenService.cs @@ -10,14 +10,13 @@ namespace Web.Services; public class TokenService : ITokenService { - private readonly IConfiguration _configuration; private readonly SymmetricSecurityKey _symmetricSecurityKey; - public TokenService(IConfiguration configuration) + public TokenService() { - _configuration = configuration; + var key = Environment.GetEnvironmentVariable("JWT_KEY")!; _symmetricSecurityKey = new SymmetricSecurityKey( - System.Text.Encoding.UTF8.GetBytes(_configuration["JwtSettings:Key"]) + System.Text.Encoding.UTF8.GetBytes(key) ); } @@ -37,8 +36,8 @@ public string GenerateToken(AppUser user, string role) Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddHours(8), SigningCredentials = credentials, - Issuer = _configuration["JwtSettings:Issuer"], - Audience = _configuration["JwtSettings:Audience"] + Issuer = Environment.GetEnvironmentVariable("JWT_ISSUER"), + Audience = Environment.GetEnvironmentVariable("JWT_AUDIENCE") }; var tokenHandler = new JwtSecurityTokenHandler(); diff --git a/src/Web/Startup/SeedData.cs b/src/Web/Startup/SeedData.cs index c1e9176..9da2e4b 100644 --- a/src/Web/Startup/SeedData.cs +++ b/src/Web/Startup/SeedData.cs @@ -5,22 +5,20 @@ namespace Web.Startup; public static class SeedData { - public static async Task Initialize(IServiceProvider serviceProvider, IConfigurationManager config) + public static async Task Initialize(IServiceProvider serviceProvider) { var userManager = serviceProvider.GetRequiredService>(); - - var id = config["RootUser:Id"]!; - var roleName = config["RootUser:RoleName"]!; - var userName = config["RootUser:UserName"]!; - var email = config["RootUser:Email"]; - var password = config["RootUser:Password"]!; - var rootUser = await userManager.FindByIdAsync(id); + var roleName = Environment.GetEnvironmentVariable("ROOTUSER_ROLE")!; + var userName = Environment.GetEnvironmentVariable("ROOTUSER_USERNAME")!; + var email = Environment.GetEnvironmentVariable("ROOTUSER_EMAIL")!; + var password = Environment.GetEnvironmentVariable("ROOTUSER_PASSWORD")!; + + var rootUser = await userManager.FindByNameAsync(userName); if (rootUser == null) { rootUser = new AppUser { - Id = id, UserName = userName, Email = email, EmailConfirmed = true diff --git a/src/Web/Startup/ServiceExtensions.Auth.cs b/src/Web/Startup/ServiceExtensions.Auth.cs index b655088..cef9bb4 100644 --- a/src/Web/Startup/ServiceExtensions.Auth.cs +++ b/src/Web/Startup/ServiceExtensions.Auth.cs @@ -6,8 +6,12 @@ namespace Web.Startup { public static partial class ServiceExtensions { - public static void ConfigureAppAuthenticationServices(this IServiceCollection services, IConfiguration config) + public static void ConfigureAppAuthenticationServices(this IServiceCollection services) { + var issuer = Environment.GetEnvironmentVariable("JWT_ISSUER"); + var audience = Environment.GetEnvironmentVariable("JWT_AUDIENCE"); + var key = Environment.GetEnvironmentVariable("JWT_KEY")!; + services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; @@ -17,10 +21,10 @@ public static void ConfigureAppAuthenticationServices(this IServiceCollection se { x.TokenValidationParameters = new TokenValidationParameters { - ValidIssuer = config["JwtSettings:Issuer"], - ValidAudience = config["JwtSettings:Audience"], + ValidIssuer = issuer, + ValidAudience = audience, IssuerSigningKey = new SymmetricSecurityKey( - Encoding.UTF8.GetBytes(config["JwtSettings:Key"]!)), + Encoding.UTF8.GetBytes(key)), ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, diff --git a/src/Web/Startup/ServiceExtensions.Cors.cs b/src/Web/Startup/ServiceExtensions.Cors.cs index bfa7066..bc6cec2 100644 --- a/src/Web/Startup/ServiceExtensions.Cors.cs +++ b/src/Web/Startup/ServiceExtensions.Cors.cs @@ -4,16 +4,15 @@ namespace Web.Startup { public static partial class ServiceExtensions { - public static void AddCorsPolicy(this IServiceCollection services) + public static void AddCorsPolicy(this IServiceCollection services, IConfiguration config) { + var origins = config.GetSection("CorsSettings:Origins").Get()!; + services.AddCors(options => { options.AddPolicy("AllowSpecificOrigins", corsPolicyBuilder => { - corsPolicyBuilder.WithOrigins( - "http://localhost:4200", - "http://external.abriment.com:30081" - ) + corsPolicyBuilder.WithOrigins(origins) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); diff --git a/src/Web/Startup/ServiceExtensions.Infra.cs b/src/Web/Startup/ServiceExtensions.Infra.cs index cc578d0..362d641 100644 --- a/src/Web/Startup/ServiceExtensions.Infra.cs +++ b/src/Web/Startup/ServiceExtensions.Infra.cs @@ -7,14 +7,18 @@ namespace Web.Startup; public static partial class ServiceExtensions { - public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration config) + public static IServiceCollection AddInfrastructureServices(this IServiceCollection services) { + var connectionString = Environment.GetEnvironmentVariable("DB_CONNECTION_STRING"); + services.AddDbContext(options => { - options.UseNpgsql(config.GetConnectionString("DefaultConnection")); + options.UseNpgsql(connectionString); }); + services.AddIdentity() .AddEntityFrameworkStores(); + return services; } } diff --git a/src/Web/Web.csproj b/src/Web/Web.csproj index f8bdcca..157fbda 100644 --- a/src/Web/Web.csproj +++ b/src/Web/Web.csproj @@ -7,6 +7,7 @@ + diff --git a/src/Web/appsettings.json b/src/Web/appsettings.json index d89dd5b..f5aeb8b 100644 --- a/src/Web/appsettings.json +++ b/src/Web/appsettings.json @@ -1,7 +1,4 @@ { - "ConnectionStrings": { - "DefaultConnection": "Server=127.0.0.1;Port=5432;Database=KakaSiah;User Id=postgres;Password=postgres;" - }, "Logging": { "LogLevel": { "Default": "Information", @@ -9,16 +6,11 @@ } }, "AllowedHosts": "*", - "JwtSettings": { - "Issuer": "http://localhost:5000", - "Audience": "http://localhost:5000", - "Key": "sjmcabnishcpasichquwh108hd29dh12wcf1hni1nci9vh9p920u1dhx08122hiokasnx89" - }, - "RootUser": { - "Id": "d2228d10-5be9-40dd-9c20-6a19343a963a", - "RoleName": "Admin", - "UserName": "root", - "Email": "root@example.com", - "Password": "Root@123" + "CorsSettings": { + "Origins": [ + "http://localhost:4200", + "http://external.abriment.com:30081", + "https://codestar.abriment.com" + ] } } \ No newline at end of file From 1f09285447707a3de5d6f033a2f3cdaefad2e530 Mon Sep 17 00:00:00 2001 From: amiralirahimii Date: Wed, 4 Sep 2024 15:47:56 +0330 Subject: [PATCH 2/2] fix: add a .env.template file --- src/Web/.env.template | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 src/Web/.env.template diff --git a/src/Web/.env.template b/src/Web/.env.template new file mode 100644 index 0000000..87e960c --- /dev/null +++ b/src/Web/.env.template @@ -0,0 +1,13 @@ +# Database Connection String +DB_CONNECTION_STRING=Server=127.0.0.1;Port=5432;Database=your_database_name;User Id=your_db_user;Password=your_db_password; + +# JWT Settings +JWT_ISSUER=http://your_issuer +JWT_AUDIENCE=http://your_audience +JWT_KEY=your_jwt_key + +# Root User Settings +ROOTUSER_ROLE=Admin +ROOTUSER_USERNAME=your_username +ROOTUSER_EMAIL=your_email +ROOTUSER_PASSWORD=your_password \ No newline at end of file