using System.Text; using AutobusApi.Application.Common.Interfaces; using AutobusApi.Infrastructure.Identity; using AutobusApi.Infrastructure.Services; using AutoubsApi.Infrastructure.Data; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; namespace AutobusApi.Infrastructure; public static class DependencyInjection { public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration) { services.AddApplicationDbContext(configuration); services.AddIdentity(configuration); services.AddServices(); services.AddAuthentication(); return services; } private static IServiceCollection AddApplicationDbContext(this IServiceCollection services, IConfiguration configuration) { services.AddDbContext(options => { options.UseNpgsql( configuration.GetConnectionString("DefaultConnection"), npgsqOptions => npgsqOptions.UseNetTopologySuite() ); }); services.AddScoped(); return services; } private static IServiceCollection AddIdentity(this IServiceCollection services, IConfiguration configuration) { services.AddDbContext(options => { options.UseNpgsql(configuration.GetConnectionString("DefaultConnection")); }); services.AddIdentity>() .AddEntityFrameworkStores() .AddDefaultTokenProviders(); return services; } private static IServiceCollection AddServices(this IServiceCollection services) { services.AddScoped(); return services; } private static IServiceCollection AddAuthenticationWithJwt(this IServiceCollection services, IConfiguration configuration) { services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.SaveToken = true; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidAudience = configuration["Jwt:Audience"], ValidIssuer = configuration["Jwt:Issuer"], ClockSkew = TimeSpan.Zero, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:IssuerSigningKey"]!)) }; }); return services; } }