GGMM/GrossesMitaines/GrossesMitainesAPI/Program.cs

79 lines
2.5 KiB
C#
Raw Normal View History

2022-10-08 14:02:05 -04:00
using GrossesMitainesAPI.Data;
using GrossesMitainesAPI.Services;
2022-10-30 16:58:47 -04:00
using Microsoft.AspNet.Identity;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
2022-10-08 14:02:05 -04:00
using Microsoft.EntityFrameworkCore;
2022-10-30 16:58:47 -04:00
using Microsoft.Extensions.Configuration;
using System.Net;
2022-10-08 14:02:05 -04:00
2022-10-17 16:07:59 -04:00
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
2022-09-27 14:26:56 -04:00
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
2022-10-17 16:07:59 -04:00
builder.Services.AddCors(options => {
options.AddPolicy(name: MyAllowSpecificOrigins,
policy => {
policy.WithOrigins("http://localhost:3000",
2022-10-18 10:08:23 -04:00
"http://localhost:3001")
.AllowAnyMethod()
.AllowAnyHeader();
2022-10-17 16:07:59 -04:00
});
});
2022-09-27 14:26:56 -04:00
builder.Services.AddControllers();
builder.Services.AddAuthorization();
builder.Services.AddAuthentication().AddIdentityCookies();
// Source: https://github.com/dotnet/aspnetcore/issues/9039
builder.Services.ConfigureApplicationCookie(o => {
o.Events = new CookieAuthenticationEvents() {
OnRedirectToLogin = (ctx) => {
if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200) {
ctx.Response.StatusCode = 401;
}
return Task.CompletedTask;
},
OnRedirectToAccessDenied = (ctx) => {
if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200) {
ctx.Response.StatusCode = 403;
}
return Task.CompletedTask;
}
};
});
2022-10-30 16:58:47 -04:00
builder.Services.AddIdentityCore<InventoryUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<InventoryContext>()
.AddSignInManager();
2022-09-27 14:26:56 -04:00
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
2022-10-08 14:02:05 -04:00
builder.Services.AddDbContextFactory<InventoryContext>(options => { options.UseSqlServer("DefaultConnection"); });
builder.Services.AddSingleton<DatabaseCacheService>();
builder.Services.BuildServiceProvider().GetRequiredService<DatabaseCacheService>();
2022-10-30 16:58:47 -04:00
2022-09-27 14:26:56 -04:00
var app = builder.Build();
// Configure the HTTP request pipeline.
2022-10-08 14:02:05 -04:00
if (app.Environment.IsDevelopment()) {
2022-09-27 14:26:56 -04:00
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
2022-10-17 16:07:59 -04:00
app.UseCors(MyAllowSpecificOrigins);
2022-09-27 14:26:56 -04:00
app.UseAuthorization();
2022-10-30 16:58:47 -04:00
app.UseAuthentication();
2022-09-27 14:26:56 -04:00
app.MapControllers();
2022-10-17 16:07:59 -04:00
app.Run();