Advertisement
hutonahill

ASP.NET, Hut's Builder

Oct 6th, 2024 (edited)
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.50 KB | Source Code | 0 0
  1. private static WebApplication buildAPI(string[] args) {
  2.             // this is classified as a minimal API.
  3.             WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
  4.            
  5.             // validate that appsettings.json contains the required endpoints
  6.             builder.Configuration.ValidateConfiguration();
  7.            
  8.             builder.Services.AddHttpContextAccessor();
  9.            
  10.             // registers the discord options and will pull values from config files (appsettings.json, etc.)
  11.             // The system will try and get a complete set of all values in the class then give
  12.             // the object to services that ask for IOptions<DiscordOptions>
  13.             builder.Services
  14.                 .AddOptions<DiscordOptions>()
  15.                 .BindConfiguration(DiscordOptions.SectionName);
  16.            
  17.             builder.Services.AddHostedService<Bot>();
  18.            
  19.             builder.Services.AddDbContext<DataContext>(options =>
  20.                 options.UseSqlite(builder.Configuration.GetConnectionString("AuthConnection")));
  21.            
  22.             builder.Services.AddControllersWithViews();
  23.  
  24.            
  25.            
  26.              // for roles
  27.              builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => {
  28.                     options.SignIn.RequireConfirmedAccount = true;
  29.                     options.Tokens.AuthenticatorTokenProvider = TokenOptions.DefaultAuthenticatorProvider;
  30.             })
  31.             .AddEntityFrameworkStores<DataContext>()
  32.             .AddDefaultTokenProviders();
  33.            
  34.            
  35.              // for no roles
  36.             /*
  37.             builder.Services.AddIdentityApiEndpoints<IdentityUser>()
  38.                 .AddEntityFrameworkStores<DataContext>();
  39.             */
  40.            
  41.             // This disables the conformed email requirement. We should Re-enable this eventually.
  42.             builder.Services.Configure<IdentityOptions>(options => {
  43.                 options.SignIn.RequireConfirmedEmail = false;
  44.                
  45.                 options.Password.RequiredLength = 9;
  46.             });
  47.            
  48.             // attach our email class.
  49.             builder.Services.AddTransient<IEmailSender<IdentityUser>, MyEmailService>();
  50.            
  51.             // control how known users interact with the API
  52.             builder.Services.AddAuthorization(options => {
  53.                
  54.                 // Define a default policy that requires nothing
  55.                 options.DefaultPolicy = new AuthorizationPolicyBuilder()
  56.                     .RequireAssertion(_ => true)
  57.                     .Build();
  58.             });
  59.            
  60.             // prove who the user is
  61.             builder.Services.AddAuthentication(options => {
  62.                     options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
  63.                     options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  64.                     options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  65.             }).AddCookie("Identity.Bearer",options => {  
  66.                 // eventually this should point to our login page
  67.                 //options.LoginPath = "/Account/Unauthorized/";
  68.                
  69.                 // eventually this will point to an access denial page
  70.                 //options.AccessDeniedPath = "/Account/Forbidden/";
  71.             })
  72.             .AddJwtBearer(options => {
  73.                
  74.                 JwtSettings? settings = builder.Configuration.GetSection("JwtSettings").Get<JwtSettings>();
  75.  
  76.                 if (settings == null) {
  77.                     throw new InvalidOperationException("Settings should not be null if this point is reached.");
  78.                 }
  79.                
  80.                 options.SaveToken = true;
  81.                
  82.                 Debug.Assert(settings.SecretKey != null, "settings.SecretKey != null");
  83.                 options.TokenValidationParameters = new TokenValidationParameters {
  84.                     ValidateIssuer = true,
  85.                     ValidateAudience = true,
  86.                     ValidateLifetime = true,
  87.                     ValidateIssuerSigningKey = true,
  88.                     ValidIssuer = settings.Issuer,
  89.                     ValidAudience = settings.Audience,
  90.                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.SecretKey)),
  91.                     ClockSkew = TimeSpan.Zero
  92.                 };
  93.  
  94.                 // DISABLE THIS FOR PRODUCTION:
  95.                 options.IncludeErrorDetails = true;
  96.  
  97.                 options.Events = new JwtBearerEvents {
  98.                     OnAuthenticationFailed = context => {
  99.                         var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
  100.                         logger.LogError($"Authentication failed. \n\tContext.Exception: '{context.Exception}'", context.Exception);
  101.                         return Task.CompletedTask;
  102.                     },
  103.                     OnChallenge = context => {
  104.                         var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
  105.                         logger.LogWarning($"OnChallenge error. \n\tcontext.Error: '{context.Error}'\n\tcontext.ErrorDescription: '{context.ErrorDescription}'", context.Error, context.ErrorDescription);
  106.                         return Task.CompletedTask;
  107.                     },
  108.                     OnMessageReceived = context => {
  109.                         var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
  110.                         logger.LogInformation("Message received: '{Token}'", context.Token);
  111.                         return Task.CompletedTask;
  112.                     },
  113.                     OnTokenValidated = context => {
  114.                         var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
  115.                         logger.LogInformation($"Token validated. \n\tcontext.SecurityToken: '{context.SecurityToken}'", context.SecurityToken);
  116.                         return Task.CompletedTask;
  117.                     }
  118.  
  119.                 };
  120.             });
  121.            
  122.             builder.Logging.ClearProviders();
  123.             builder.Logging.AddConsole();
  124.             builder.Logging.AddDebug();
  125.            
  126.             builder.Services.AddHttpContextAccessor();
  127.  
  128.            
  129.             // Add services to the container.
  130.             // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  131.             builder.Services.AddEndpointsApiExplorer();
  132.             builder.Services.AddSwaggerGen(options => {
  133.                 options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme {
  134.                     In = ParameterLocation.Header,
  135.                     Name = "Authorization",
  136.                     Type = SecuritySchemeType.ApiKey
  137.                 });
  138.                 options.OperationFilter<SecurityRequirementsOperationFilter>();
  139.             });
  140.            
  141.             Log.Logger = new LoggerConfiguration()
  142.                 .MinimumLevel.Information()
  143.                 .WriteTo.File("logs/general/api-logs-.txt", rollingInterval: RollingInterval.Day)
  144.                 // Configure Serilog for API endpoint logging
  145.                 .WriteTo.Logger(lc => lc
  146.                     .WriteTo.File("logs/endpoints/endpoint-logs-.txt", rollingInterval: RollingInterval.Day))
  147.                 .CreateLogger();
  148.            
  149.             builder.Logging.AddSerilog();
  150.  
  151.             return builder.Build();
  152.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement