/
qwiklly
/
arc-server
Обзор
Документация
Войти
/
qwiklly
/
arc-server
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
trunk
examples/AppRemoteConfig.SampleApp/Program.cs
220 строк
7 KB
Nikolai
Configure FilesPath to serve static files from 'wwwroot' directory
19 дек 2024, 22:35
19 дек 2024, 22:35
0f0a7d5
Код
Авторство
О чём код?
using System.IdentityModel.Tokens.Jwt; using System.Text.Json; using System.Text.Json.Serialization; using AppRemoteConfig.Controllers; using AppRemoteConfig.Models; using AppRemoteConfig.Models.Database; using AppRemoteConfig.Services; using AppRemoteConfig.Services.Interfaces; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Server; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.FileProviders; using Microsoft.IdentityModel.Tokens; using Serilog; var builder = WebApplication.CreateBuilder(args); var connectionString = builder.Configuration.GetConnectionString("ArcContext"); var appSettings = builder.Configuration.GetSection(nameof(AppSettings)).Get<AppSettings>(); if (appSettings == null) { throw new Exception("App settings are null"); } builder.Services.AddSingleton<IAppSettings>(appSettings); builder.Services.AddCors(options => { options.AddPolicy("AllowAll", builder => { builder.AllowAnyMethod() .AllowAnyHeader() .SetIsOriginAllowed(origin => true) .AllowCredentials(); }); }); builder.Services.AddLogging(s => s.AddSerilog( new LoggerConfiguration() .ReadFrom.Configuration(builder.Configuration) .CreateLogger(), true)); builder.Services.AddHttpContextAccessor(); builder.Services.AddScoped<HttpContextAccessor>(); builder.Services.AddDbContext<ApplicationContext>(options => options.UseNpgsql( connectionString, x => x.MigrationsAssembly("AppRemoteConfig"))); builder.Services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString; } ); builder.Services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie(options => { options.ExpireTimeSpan = TimeSpan.FromDays(14); options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter; options.SlidingExpiration = true; options.Events = new CookieAuthenticationEvents(); options.Cookie.SameSite = SameSiteMode.Lax; options.Cookie.HttpOnly = true; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.Cookie.IsEssential = true; }) .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options => { // this is my Authorization Server Port options.Authority = $"{appSettings.ProviderHost}"; options.ClientId = $"{appSettings.ClientId}"; options.ClientSecret = "123456789"; options.ResponseType = "code"; options.CallbackPath = "/signin-oidc"; options.SaveTokens = true; options.Scope.Add("email"); options.Scope.Add("phone"); options.NonceCookie.SameSite = SameSiteMode.Lax; options.NonceCookie.HttpOnly = true; options.NonceCookie.SecurePolicy = CookieSecurePolicy.Always; options.NonceCookie.IsEssential = true; options.CorrelationCookie.SameSite = SameSiteMode.Lax; options.CorrelationCookie.HttpOnly = true; options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always; options.CorrelationCookie.IsEssential = true; if (builder.Environment.IsDevelopment()) { options.RequireHttpsMetadata = false; // allow providerHost=http://localhost:7276 in dev mode options.Events.OnRedirectToIdentityProvider = async (context) => { context.ProtocolMessage.RedirectUri = "http://localhost:5000/signin-oidc"; await Task.FromResult(0); }; } options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = false, SignatureValidator = (token, validationParameters) => { var jwt = new JwtSecurityToken(token); return jwt; }, }; options.UsePkce = true; }); builder.Services.AddTransient<IEmailSender, EmailSender>(); builder.Services.AddIdentity<AppUser, IdentityRole<Guid>>() .AddEntityFrameworkStores<ApplicationContext>() .AddDefaultTokenProviders(); builder.Services.Configure<IdentityOptions>(options => { // Password settings options.Password.RequireDigit = false; options.Password.RequiredLength = 6; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequireLowercase = false; // Lockout settings options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromHours(12); options.Lockout.MaxFailedAccessAttempts = 10; options.Lockout.AllowedForNewUsers = true; // User settings options.User.RequireUniqueEmail = false; }); builder.Services.ConfigureApplicationCookie(options => { // Cookie settings options.Cookie.HttpOnly = true; options.ExpireTimeSpan = TimeSpan.FromMinutes(5); options.LoginPath = "/Identity/Account/Login"; options.AccessDeniedPath = "/Identity/Account/AccessDenied"; options.SlidingExpiration = true; }); builder.Services.AddScoped<IHostEnvironmentAuthenticationStateProvider>(sp => { var provider = (ServerAuthenticationStateProvider)sp.GetRequiredService<AuthenticationStateProvider>(); return provider; }); if (builder.Environment.IsDevelopment()) { builder.Services.AddRazorPages().AddRazorRuntimeCompilation(); } else { builder.Services.AddRazorPages(); } builder.Services.AddServerSideBlazor(); builder.Services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<AppUser>>(); builder.Services.AddScoped<IUserService, UserService>(); builder.Services.AddScoped<IOrganizationsService, OrganizationsService>(); builder.Services.AddScoped<IApplicationService, ApplicationService>(); var app = builder.Build(); app.UseCors("AllowAll"); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseHttpsRedirection(); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseStaticFiles(); var staticFilesPath = Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "src", "AppRemoteConfig.UI", "wwwroot"); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(staticFilesPath), RequestPath = "/AppRemoteConfig.UI" }); app.UseCookiePolicy(); app.UseRouting(); app.Use(async (context, next) => { await next.Invoke(); var data = context.User.Identity?.IsAuthenticated; var path = context.Request.Path; var a = ""; }); app.UseAuthentication(); app.UseAuthorization(); app.MapRazorPages(); app.MapControllers(); app.MapBlazorHub(); app.MapFallbackToPage("/_Host"); app.Run();