autobus-api_old/AutobusApi.Infrastructure/DependencyInjection.cs
2023-11-15 19:00:34 +02:00

90 lines
3.1 KiB
C#

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<ApplicationDbContext>(options =>
{
options.UseNpgsql(
configuration.GetConnectionString("DefaultConnection"),
npgsqOptions => npgsqOptions.UseNetTopologySuite()
);
});
services.AddScoped<IApplicationDbContext, ApplicationDbContext>();
return services;
}
private static IServiceCollection AddIdentity(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<ApplicationIdentityDbContext>(options =>
{
options.UseNpgsql(configuration.GetConnectionString("DefaultConnection"));
});
services.AddIdentity<ApplicationUser, IdentityRole<int>>()
.AddEntityFrameworkStores<ApplicationIdentityDbContext>()
.AddDefaultTokenProviders();
return services;
}
private static IServiceCollection AddServices(this IServiceCollection services)
{
services.AddScoped<IIdentityService, IdentityService>();
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;
}
}