|
| 1 | +using System.Text; |
| 2 | +using System.Threading.RateLimiting; |
| 3 | +using Asp.Versioning; |
| 4 | +using Microsoft.AspNetCore.Authentication.JwtBearer; |
| 5 | +using Microsoft.AspNetCore.Identity; |
| 6 | +using Microsoft.IdentityModel.Tokens; |
| 7 | +using WebApiBestPractices.Api.Filters; |
| 8 | +using WebApiBestPractices.Api.Security; |
| 9 | +using WebApiBestPractices.Application.Services; |
| 10 | +using WebApiBestPractices.Domain.Contracts; |
| 11 | +using WebApiBestPractices.Infrastructure.Repositories; |
| 12 | + |
| 13 | +namespace WebApiBestPractices.Api.Extensions; |
| 14 | + |
| 15 | +public static class ServiceExtensions |
| 16 | +{ |
| 17 | + public const string CorsPolicy = "CorsPolicy"; |
| 18 | + public const string OwnersCachePolicy = "Owners"; |
| 19 | + public const string OwnersCacheTag = "owners"; |
| 20 | + public const string PerClientRateLimit = "PerClient"; |
| 21 | + |
| 22 | + public static void ConfigureCors(this IServiceCollection services, IConfiguration configuration) => |
| 23 | + services.AddCors(options => |
| 24 | + options.AddPolicy(CorsPolicy, policy => policy |
| 25 | + .WithOrigins(configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? []) |
| 26 | + .AllowAnyMethod() |
| 27 | + .AllowAnyHeader())); |
| 28 | + |
| 29 | + public static void ConfigureApplicationServices(this IServiceCollection services) |
| 30 | + { |
| 31 | + services.AddSingleton<IOwnerRepository, InMemoryOwnerRepository>(); |
| 32 | + services.AddScoped<IOwnerService, OwnerService>(); |
| 33 | + services.AddScoped<ValidateOwnerExistsFilter>(); |
| 34 | + services.AddScoped<IPasswordHasher<AppUser>, PasswordHasher<AppUser>>(); |
| 35 | + services.AddScoped<AccountService>(); |
| 36 | + services.AddScoped<OwnerIdProtector>(); |
| 37 | + services.AddDataProtection(); |
| 38 | + services.AddHybridCache(); |
| 39 | + } |
| 40 | + |
| 41 | + public static void ConfigureVersioning(this IServiceCollection services) => |
| 42 | + services.AddApiVersioning(options => |
| 43 | + { |
| 44 | + options.DefaultApiVersion = new ApiVersion(1, 0); |
| 45 | + options.AssumeDefaultVersionWhenUnspecified = true; |
| 46 | + options.ReportApiVersions = true; |
| 47 | + options.ApiVersionReader = ApiVersionReader.Combine( |
| 48 | + new QueryStringApiVersionReader("api-version"), |
| 49 | + new HeaderApiVersionReader("api-version")); |
| 50 | + }) |
| 51 | + .AddMvc(); |
| 52 | + |
| 53 | + public static void ConfigureOutputCache(this IServiceCollection services) => |
| 54 | + services.AddOutputCache(options => |
| 55 | + options.AddPolicy(OwnersCachePolicy, policy => policy |
| 56 | + .Expire(TimeSpan.FromSeconds(30)) |
| 57 | + .SetVaryByHeader("Accept") |
| 58 | + .Tag(OwnersCacheTag))); |
| 59 | + |
| 60 | + public static void ConfigureRateLimiting(this IServiceCollection services, IConfiguration configuration) |
| 61 | + { |
| 62 | + var permitLimit = configuration.GetValue("RateLimiting:PermitLimit", 100); |
| 63 | + |
| 64 | + services.AddRateLimiter(options => |
| 65 | + { |
| 66 | + options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; |
| 67 | + options.AddPolicy(PerClientRateLimit, httpContext => |
| 68 | + RateLimitPartition.GetFixedWindowLimiter( |
| 69 | + partitionKey: httpContext.User.Identity?.Name |
| 70 | + ?? httpContext.Connection.RemoteIpAddress?.ToString() |
| 71 | + ?? "anonymous", |
| 72 | + factory: _ => new FixedWindowRateLimiterOptions |
| 73 | + { |
| 74 | + PermitLimit = permitLimit, |
| 75 | + Window = TimeSpan.FromMinutes(1), |
| 76 | + QueueLimit = 0 |
| 77 | + })); |
| 78 | + }); |
| 79 | + } |
| 80 | + |
| 81 | + public static void ConfigureJwt(this IServiceCollection services, IConfiguration configuration) |
| 82 | + { |
| 83 | + var jwtSettings = configuration.GetSection("JwtSettings"); |
| 84 | + var secretKey = jwtSettings["SecretKey"] |
| 85 | + ?? throw new InvalidOperationException("JwtSettings:SecretKey is not configured."); |
| 86 | + |
| 87 | + services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) |
| 88 | + .AddJwtBearer(options => |
| 89 | + { |
| 90 | + options.TokenValidationParameters = new TokenValidationParameters |
| 91 | + { |
| 92 | + ValidateIssuer = true, |
| 93 | + ValidateAudience = true, |
| 94 | + ValidateLifetime = true, |
| 95 | + ValidateIssuerSigningKey = true, |
| 96 | + ValidIssuer = jwtSettings["ValidIssuer"], |
| 97 | + ValidAudience = jwtSettings["ValidAudience"], |
| 98 | + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)) |
| 99 | + }; |
| 100 | + }); |
| 101 | + } |
| 102 | +} |
0 commit comments