Skip to content

Commit

Permalink
Merge pull request #176 from jihadkhawaja/Fluent-integration
Browse files Browse the repository at this point in the history
Moved some configurations outside server library
  • Loading branch information
YoussofKhawaja committed Apr 24, 2024
2 parents 4b94f20 + 5f2a081 commit e6d5f62
Show file tree
Hide file tree
Showing 3 changed files with 113 additions and 149 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/MSTest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,4 @@ jobs:
username: ${{ secrets.REMOTE_USER }}
key: ${{ secrets.KEY }}
script: |
docker exec postgres psql -U postgres -c "drop database \"egroo-dev-test\" WITH ( FORCE );"
docker exec postgres psql -U ${{ secrets.REMOTE_USER_DB }} -c "drop database \"egroo-dev-test\" WITH ( FORCE );"
106 changes: 106 additions & 0 deletions src/Egroo.Server/Program.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,112 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Serilog;
using System.Text;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

//logger
builder.Host.UseSerilog((ctx, lc) => lc.ReadFrom.Configuration(ctx.Configuration));

#region CORS
var allowedOrigins = builder.Configuration.GetSection("Api:AllowedOrigins").Get<string[]>();

#if DEBUG
allowedOrigins = null;
#endif

if (allowedOrigins is null || allowedOrigins.Length == 0)
{
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
policy =>
{
policy.AllowAnyOrigin();
policy.AllowAnyHeader();
policy.AllowAnyMethod();
});
});
}
else
{
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
policy =>
{
policy.WithOrigins(allowedOrigins);
policy.AllowAnyHeader();
policy.AllowAnyMethod();
});
});
}
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition(name: "Bearer", securityScheme: new OpenApiSecurityScheme
{
Name = "Authorization",
Description = "Enter the Bearer Authorization string as following: `Bearer Generated-JWT-Token`",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Name = "Bearer",
In = ParameterLocation.Header,
Reference = new OpenApiReference
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
},
new List<string>()
}
});
});
#endregion
#region JWT
string jwtKey = builder.Configuration.GetSection("Secrets")["Jwt"]
?? throw new NullReferenceException(nameof(jwtKey));

builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters.ValidateIssuerSigningKey = true;
options.TokenValidationParameters.IssuerSigningKey =
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey));
options.TokenValidationParameters.ValidateIssuer = false;
options.TokenValidationParameters.ValidateAudience = false;
options.TokenValidationParameters.ValidateLifetime = true;
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/chathub")))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
#endregion

builder.Services.AddAuthorization();

// Add Egroo chat services
builder.Services.AddChatServices()
.WithConfiguration(builder.Configuration)
Expand Down Expand Up @@ -33,6 +135,10 @@

app.UseRouting();

app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseAuthorization();

// Use Egroo chat services
app.UseChatServices();

Expand Down
154 changes: 6 additions & 148 deletions src/jihadkhawaja.chat.server/Register.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,10 @@
using jihadkhawaja.chat.server.Interfaces;
using jihadkhawaja.chat.server.Services;
using jihadkhawaja.chat.shared.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Net;
using System.Text;
using System.Threading.RateLimiting;

public enum DatabaseEnum
{
Expand Down Expand Up @@ -41,11 +34,6 @@ public static void UseChatServices(this WebApplication app)
}
}

app.UseCors("CorsPolicy");
app.UseRateLimiter();
app.UseAuthentication();
app.UseAuthorization();

//hubs
app.MapHub<ChatHub>("/chathub", options =>
{
Expand All @@ -56,14 +44,14 @@ public static void UseChatServices(this WebApplication app)

public class ChatServiceBuilder
{
public string DbConnectionStringKey { get; private set; }
public string? DbConnectionStringKey { get; private set; }
public DatabaseEnum SelectedDatabase { get; private set; }
public string CurrentExecutionAssemblyName { get; private set; }
public string? CurrentExecutionAssemblyName { get; private set; }
public bool AutoMigrateDatabase { get; private set; }

private readonly IServiceCollection _services;
private IConfiguration _configuration;
private Type _executionClassType;
private IConfiguration? _configuration;
private Type? _executionClassType;
private DatabaseEnum _databaseEnum;
private bool _autoMigrateDatabase = true;
private string _dbConnectionStringKey = "DefaultConnection";
Expand Down Expand Up @@ -111,138 +99,12 @@ public IServiceCollection Build()
System.Reflection.Assembly.GetAssembly(_executionClassType).GetName().Name;

Check warning on line 99 in src/jihadkhawaja.chat.server/Register.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'type' in 'Assembly? Assembly.GetAssembly(Type type)'.

Check warning on line 99 in src/jihadkhawaja.chat.server/Register.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
AutoMigrateDatabase = _autoMigrateDatabase;

ConfigureApi(_services);
ConfigureJwtAuthentication(_services);
ConfigureSignalR(_services);
ConfigureDatabase(_services);
ConfigureAuthorization(_services);
ConfigureEntityServices(_services);
ConfigureDatabase(_services);
ConfigureSignalR(_services);

return _services;
}

private void ConfigureApi(IServiceCollection services)
{
//API Rate Limiter
services.AddRateLimiter(options =>
{
options.RejectionStatusCode = 429;
options.AddFixedWindowLimiter("Api_Global", options =>
{
options.AutoReplenishment = true;
options.PermitLimit = 10;
options.Window = TimeSpan.FromMinutes(1);
});
options.AddPolicy("Api", httpContext =>
RateLimitPartition.GetFixedWindowLimiter(httpContext.Connection.RemoteIpAddress,
partition => new FixedWindowRateLimiterOptions
{
AutoReplenishment = true,
PermitLimit = 10,
Window = TimeSpan.FromSeconds(1)
}));
options.AddPolicy("None", httpContext =>
RateLimitPartition.GetNoLimiter(IPAddress.Loopback));
});
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition(name: "Bearer", securityScheme: new OpenApiSecurityScheme
{
Name = "Authorization",
Description = "Enter the Bearer Authorization string as following: `Bearer Generated-JWT-Token`",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Name = "Bearer",
In = ParameterLocation.Header,
Reference = new OpenApiReference
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
},
new List<string>()
}
});
});

//CORS
var allowedOrigins = _configuration.GetSection("Api:AllowedOrigins").Get<string[]>();

#if DEBUG
allowedOrigins = null;
#endif

if (allowedOrigins is null || allowedOrigins.Length == 0)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
policy =>
{
policy.AllowAnyOrigin();
policy.AllowAnyHeader();
policy.AllowAnyMethod();
});
});
}
else
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
policy =>
{
policy.WithOrigins(allowedOrigins);
policy.AllowAnyHeader();
policy.AllowAnyMethod();
});
});
}
}
private void ConfigureJwtAuthentication(IServiceCollection services)
{
string jwtKey = _configuration.GetSection("Secrets")["Jwt"]
?? throw new NullReferenceException(nameof(jwtKey));

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters.ValidateIssuerSigningKey = true;
options.TokenValidationParameters.IssuerSigningKey =
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey));
options.TokenValidationParameters.ValidateIssuer = false;
options.TokenValidationParameters.ValidateAudience = false;
options.TokenValidationParameters.ValidateLifetime = true;
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/chathub")))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
}
private void ConfigureSignalR(IServiceCollection services)
{
services.AddSignalR();
Expand All @@ -251,10 +113,6 @@ private void ConfigureDatabase(IServiceCollection services)
{
services.AddDbContext<DataContext>();
}
private void ConfigureAuthorization(IServiceCollection services)
{
services.AddAuthorization();
}
private void ConfigureEntityServices(IServiceCollection services)
{
services.AddScoped<IEntity<User>, EntityService<User>>();
Expand Down

0 comments on commit e6d5f62

Please sign in to comment.