mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 17:11:10 +00:00
Implements authentication system
This commit is contained in:
1 parent
38829d64ff
commit
a6dcf65d1c
103 files changed
+2983
-454
No files matched your search
+80
-1
@@ -1,9 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using FastEndpoints.Swagger;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Json;
|
||||
using Microsoft.AspNetCore.Mvc.Infrastructure;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.RateLimiting;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Common.DependencyInjection;
|
||||
@@ -17,9 +28,12 @@ public static class PresentationApiLayerServices
|
||||
/// Registers the services of the Presentation API layer into the dependency injection container.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to add the services to.</param>
|
||||
/// <param name="configuration">Application configuration properties.</param>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services)
|
||||
public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddMemoryCache(); // used for the tracking involved in authentication rate limiting
|
||||
services.AddProblemDetails();
|
||||
|
||||
services.Configure<JsonOptions>(jsonOptions =>
|
||||
{
|
||||
@@ -28,6 +42,71 @@ public static class PresentationApiLayerServices
|
||||
jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
|
||||
});
|
||||
|
||||
services.AddRateLimiter(options =>
|
||||
{
|
||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||
options.OnRejected = async (context, cancellationToken) =>
|
||||
{
|
||||
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
|
||||
context.HttpContext.Response.ContentType = "application/problem+json";
|
||||
|
||||
var problem = new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7231#section-6.5.29",
|
||||
title = "TooManyRequests", // TODO: implement translation?
|
||||
status = StatusCodes.Status429TooManyRequests,
|
||||
detail = "Too many attempts. Please try again later.",
|
||||
retryAfter = "15"
|
||||
};
|
||||
|
||||
await context.HttpContext.Response.WriteAsJsonAsync(problem, cancellationToken);
|
||||
};
|
||||
options.AddFixedWindowLimiter("authenticationPolicy", config =>
|
||||
{
|
||||
config.PermitLimit = 10; // allow 10 attempts
|
||||
config.Window = TimeSpan.FromMinutes(15); // within 15 minute window
|
||||
config.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
|
||||
config.QueueLimit = 0; // don't queue requests
|
||||
});
|
||||
});
|
||||
|
||||
// add authentication and specify the JWT scheme to check tokens against
|
||||
services.AddAuthentication(defaultScheme: JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters()
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = configuration["JwtSettings:Issuer"],
|
||||
ValidAudience = configuration["JwtSettings:Audience"],
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSettings:SecretKey"]!)),
|
||||
};
|
||||
|
||||
options.Events = new JwtBearerEvents
|
||||
{
|
||||
OnChallenge = context => // event triggered when authentication is not successful for whatever reason
|
||||
{
|
||||
context.HandleResponse(); // prevent the default 401 response
|
||||
// set the response status code to 401 Unauthorized
|
||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
context.Response.ContentType = "application/problem+json";
|
||||
|
||||
IProblemDetailsService problemDetailsService = context.HttpContext.RequestServices.GetRequiredService<IProblemDetailsService>();
|
||||
return context.Response.WriteAsJsonAsync(new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = StatusCodes.Status401Unauthorized,
|
||||
title = "Unauthorized",
|
||||
detail = "You are not authorized",
|
||||
instance = context.HttpContext.Request.Path
|
||||
});
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
services.AddAuthorization();
|
||||
|
||||
services.AddFastEndpoints(
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
namespace Lumina.Presentation.Api.Common.Http;
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Constants shared by HttpContext across a HTTP request (avoid magic strings).
|
||||
@@ -8,4 +6,4 @@ namespace Lumina.Presentation.Api.Common.Http;
|
||||
public static class HttpContextItemKeys
|
||||
{
|
||||
public const string ERRORS = "errors";
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
|
||||
namespace Lumina.Presentation.Api.Common.Routes.Maintenance;
|
||||
|
||||
/// <summary>
|
||||
/// Class for the collection of routes defined in this API.
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace Lumina.Presentation.Api.Common.Routes.Maintenance;
|
||||
|
||||
/// <summary>
|
||||
/// Class for the collection of routes defined in this API.
|
||||
/// </summary>
|
||||
public static partial class ApiRoutes
|
||||
{
|
||||
/// <summary>
|
||||
/// Routes for the Initialization route.
|
||||
/// </summary>
|
||||
public static class Initialization
|
||||
{
|
||||
public const string SETUP_APPLICATION = "/initialization";
|
||||
public const string CHECK_INITIALIZATION = "/initialization";
|
||||
}
|
||||
}
|
||||
@@ -12,5 +12,7 @@ public static partial class ApiRoutes
|
||||
{
|
||||
public const string REGISTER_ACCOUNT = "/auth/register";
|
||||
public const string LOGIN_ACCOUNT = "/auth/login";
|
||||
public const string RECOVER_PASSWORD = "/auth/recover-password";
|
||||
public const string CHANGE_PASSWORD = "/auth/change-password";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace Lumina.Presentation.Api.Common.Routes.UsersManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Class for the collection of routes defined in this API.
|
||||
/// </summary>
|
||||
public static partial class ApiRoutes
|
||||
{
|
||||
/// <summary>
|
||||
/// Routes for the Users route.
|
||||
/// </summary>
|
||||
public static class Users
|
||||
{
|
||||
public const string GET_USER_BY_ID = "/users/{id}";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user