survey-webapp/SurveyBackend/SurveyBackend.API/Program.cs

80 lines
No EOL
2.6 KiB
C#

using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using SurveyBackend.Core.Repositories;
using SurveyBackend.Core.Services;
using SurveyBackend.Infrastructure;
using SurveyBackend.Infrastructure.Data;
using SurveyBackend.Infrastructure.Repositories;
using SurveyBackend.Infrastructure.Services;
using SurveyLib.Core.Repositories;
using SurveyLib.Core.Services;
using SurveyLib.Infrastructure.EFCore.Data;
using SurveyLib.Infrastructure.EFCore.Repositories;
using SurveyLib.Infrastructure.EFCore.Services;
namespace SurveyBackend;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
AuthOptions.MakeOptions(builder.Configuration, Environment.GetEnvironmentVariable("JWT_SECRET_KEY"));
builder.Services.AddAuthorization();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<SurveyDbContext>(provider => provider.GetRequiredService<ApplicationDbContext>());
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IPasswordHasher, Sha256PasswordHasher>();
builder.Services.AddScoped<AuthorizationService>();
builder.Services.AddScoped<ISurveyRepository, SurveyRepository>();
builder.Services.AddScoped<ISurveyService, SurveyService>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = AuthOptions.Issuer,
ValidAudience = AuthOptions.Audience,
IssuerSigningKey = AuthOptions.SymmetricSecurityKey
};
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}