Skip to content

Commit

Permalink
Merge pull request #84 from Tynab/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
Tynab authored Feb 2, 2024
2 parents 28856b3 + 773663b commit b8ec758
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 130 deletions.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,13 @@ var dto = json.Deserialize<JsonDto>();

### NOTE

- Elastic.Apm.NetCoreAll (~1.24.0) spam logs
- Elastic.Apm.NetCoreAll (v.1.24.x and above) is spam logs.
- DotNetCap.CAP (v.7.x.x and above) is MongoDB error.
- Do not [Remove Unused References...] in layers:
- Host:
- Microsoft.EntityFrameworkCore.Tools
- DotNetCap.CAP...
- Serilog...
- Volo.Abp.EntityFrameworkCore.SqlServer
- Domain.Shared:
- Microsoft.Extensions.FileProviders.Embedded
46 changes: 46 additions & 0 deletions host/YANLib.HttpApi.Host/Middlewares/SwaggerBasicAuthMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;
using YANLib.Core;
using static System.Convert;
using static System.DateTime;
using static System.Net.HttpStatusCode;
using static System.StringSplitOptions;
using static System.Text.Encoding;

namespace YANLib.Middlewares;

public class SwaggerBasicAuthMiddleware(RequestDelegate next, IConfiguration configuration)
{
private readonly RequestDelegate _next = next;
private readonly IConfiguration _configuration = configuration;

public async Task Invoke(HttpContext context)
{
if (context.Request.Path.StartsWithSegments("/swagger"))
{
string authHeader = context.Request.Headers["Authorization"];

if (authHeader.IsNotWhiteSpaceAndNull() && authHeader.StartsWith("Basic "))
{
var decoded = UTF8.GetString(FromBase64String(authHeader.Split(' ', 2, RemoveEmptyEntries)[1]?.Trim()))?.Split(':', 2);

if (IsAuthorized(decoded[0], decoded[1]))
{
await _next.Invoke(context);

return;
}
}

context.Response.Headers["WWW-Authenticate"] = "Basic";
context.Response.StatusCode = Unauthorized.ToInt();
}
else
{
await _next.Invoke(context);
}
}

private bool IsAuthorized(string username, string password) => username.Equals($"{_configuration["Auth:Username"]}{Today.Day}") && password.Equals($"{_configuration["Auth:Password"]}{Now.Minute}");
}

This file was deleted.

67 changes: 5 additions & 62 deletions host/YANLib.HttpApi.Host/YANLibHttpApiHostModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
using Volo.Abp.Swashbuckle;
using YANLib.Core;
using YANLib.EntityFrameworkCore;
using YANLib.Middlewares;
using YANLib.Utilities;
using static Elastic.Apm.Agent;
using static HealthChecks.UI.Client.UIResponseWriter;
Expand All @@ -39,16 +40,6 @@
using static System.Convert;
using static System.StringSplitOptions;

#if DEBUG
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using YANLib.Middlewares;
using static Microsoft.OpenApi.Models.ParameterLocation;
using static Microsoft.OpenApi.Models.SecuritySchemeType;
using static System.Net.HttpStatusCode;
using static System.Threading.Tasks.Task;
#endif

namespace YANLib;

[DependsOn(
Expand Down Expand Up @@ -120,27 +111,6 @@ private static void ConfigureAuthentication(ServiceConfigurationContext context,
o.Authority = configuration["AuthServer:Authority"];
o.RequireHttpsMetadata = ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]);
o.Audience = configuration["AuthServer:ApiName"];

#if DEBUG
o.Events = new JwtBearerEvents
{
OnMessageReceived = async c =>
{
string authorization = c.Request.Headers.Authorization;

if (authorization == configuration["Authorization:Bearer"])
{
await CompletedTask;
}
else
{
c.Response.StatusCode = Unauthorized.ToInt();
c.Response.ContentType = "application/json";
await c.Response.WriteAsync("Access Denied");
}
}
};
#endif
});

private static void ConfigureSwaggerServices(ServiceConfigurationContext context, IConfiguration configuration)
Expand All @@ -165,30 +135,6 @@ private static void ConfigureSwaggerServices(ServiceConfigurationContext context
Version = "test"
});

#if DEBUG
o.AddSecurityDefinition("Authorization", new OpenApiSecurityScheme
{
In = Header,
Description = "Please insert JWT with Bearer into field",
Name = "Authorization",
Type = ApiKey
});

o.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Id = "Authorization",
Type = ReferenceType.SecurityScheme
}
}, new List<string>()
}
});
#endif

o.CustomSchemaIds(t => t.FullName.Replace("+", "."));
o.HideAbpEndpoints();
o.EnableAnnotations();
Expand Down Expand Up @@ -265,9 +211,9 @@ public override void OnApplicationInitialization(ApplicationInitializationContex
var app = context.GetApplicationBuilder();

_ = context.GetEnvironment().IsDevelopment() ? app.UseDeveloperExceptionPage() : app.UseHsts();
_ = app.UseAllElasticApm(context.GetConfiguration()); // required first
_ = Subscribe(new HttpDiagnosticsSubscriber()); // required second
_ = Subscribe(new EfCoreDiagnosticsSubscriber()); // required third
_ = app.UseAllElasticApm(context.GetConfiguration()); // primary required
_ = Subscribe(new HttpDiagnosticsSubscriber()); // secondary required
_ = Subscribe(new EfCoreDiagnosticsSubscriber()); // secondary required
_ = app.UseHttpsRedirection();
_ = app.UseCorrelationId();
_ = app.UseStaticFiles();
Expand All @@ -280,14 +226,11 @@ public override void OnApplicationInitialization(ApplicationInitializationContex
_ = o.AddSupportedUICultures("vi");
});

#if DEBUG
_ = app.UseMiddleware<UnauthorizedHandlerMiddleware>();
#endif

_ = app.UseCors();
_ = app.UseAuthentication();
_ = app.UseAuthorization();
_ = app.UseSwagger();
_ = app.UseMiddleware<SwaggerBasicAuthMiddleware>();

_ = app.UseAbpSwaggerUI(c =>
{
Expand Down
5 changes: 3 additions & 2 deletions host/YANLib.HttpApi.Host/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
"ConnectionStrings": {
"Default": "Server=192.168.1.8;Database=YANLIB;User ID=sa;Password=admin123@;TrustServerCertificate=true"
},
"Authorization": {
"Bearer": "eWFubGliLnRva2VuLmRldg=="
"Auth": {
"Username": "dev",
"Password": "dev123@"
},
"Redis": {
"Configuration": "192.168.1.8,password=admin123@"
Expand Down
5 changes: 3 additions & 2 deletions host/YANLib.HttpApi.Host/appsettings.Production.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
"ConnectionStrings": {
"Default": "Server=mssql;Database=YANLIB;User ID=sa;Password=admin123@;TrustServerCertificate=true"
},
"Authorization": {
"Bearer": "eWFubGliLnRva2VuLnByb2Q="
"Auth": {
"Username": "prod",
"Password": "prod123@"
},
"Redis": {
"Configuration": "redis,password=admin123@"
Expand Down
3 changes: 1 addition & 2 deletions src/YANLib.HttpApi/Controllers/DeveloperTypeController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.Annotations;
using System.ComponentModel.DataAnnotations;
Expand Down

0 comments on commit b8ec758

Please sign in to comment.