SessionZero/SessionZeroBackend/Program.cs
2025-03-27 23:33:23 -05:00

76 lines
2.2 KiB
C#

using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using SessionZeroBackend;
using SessionZeroBackend.Models;
var builder = WebApplication.CreateBuilder(args);
ConfigureServices(builder);
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "SessionZero API V1");
});
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
void ConfigureServices(WebApplicationBuilder builder)
{
var configuration = builder.Configuration;
var services = builder.Services;
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseNpgsql(
configuration.GetConnectionString("DefaultConnection") ??
throw new NullReferenceException("No connection string found."));
});
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
var key = Encoding.ASCII.GetBytes(configuration["Jwt:Key"]);
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = configuration["Jwt:Issuer"],
ValidAudience = configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo {Title = "SessionZero API", Version = "v1"});
});
}