Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private static WebApplication buildAPI(string[] args) {
- // this is classified as a minimal API.
- WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
- // validate that appsettings.json contains the required endpoints
- builder.Configuration.ValidateConfiguration();
- builder.Services.AddHttpContextAccessor();
- // registers the discord options and will pull values from config files (appsettings.json, etc.)
- // The system will try and get a complete set of all values in the class then give
- // the object to services that ask for IOptions<DiscordOptions>
- builder.Services
- .AddOptions<DiscordOptions>()
- .BindConfiguration(DiscordOptions.SectionName);
- builder.Services.AddHostedService<Bot>();
- builder.Services.AddDbContext<DataContext>(options =>
- options.UseSqlite(builder.Configuration.GetConnectionString("AuthConnection")));
- builder.Services.AddControllersWithViews();
- // for roles
- builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => {
- options.SignIn.RequireConfirmedAccount = true;
- options.Tokens.AuthenticatorTokenProvider = TokenOptions.DefaultAuthenticatorProvider;
- })
- .AddEntityFrameworkStores<DataContext>()
- .AddDefaultTokenProviders();
- // for no roles
- /*
- builder.Services.AddIdentityApiEndpoints<IdentityUser>()
- .AddEntityFrameworkStores<DataContext>();
- */
- // This disables the conformed email requirement. We should Re-enable this eventually.
- builder.Services.Configure<IdentityOptions>(options => {
- options.SignIn.RequireConfirmedEmail = false;
- options.Password.RequiredLength = 9;
- });
- // attach our email class.
- builder.Services.AddTransient<IEmailSender<IdentityUser>, MyEmailService>();
- // control how known users interact with the API
- builder.Services.AddAuthorization(options => {
- // Define a default policy that requires nothing
- options.DefaultPolicy = new AuthorizationPolicyBuilder()
- .RequireAssertion(_ => true)
- .Build();
- });
- // prove who the user is
- builder.Services.AddAuthentication(options => {
- options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
- options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
- options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
- }).AddCookie("Identity.Bearer",options => {
- // eventually this should point to our login page
- //options.LoginPath = "/Account/Unauthorized/";
- // eventually this will point to an access denial page
- //options.AccessDeniedPath = "/Account/Forbidden/";
- })
- .AddJwtBearer(options => {
- JwtSettings? settings = builder.Configuration.GetSection("JwtSettings").Get<JwtSettings>();
- if (settings == null) {
- throw new InvalidOperationException("Settings should not be null if this point is reached.");
- }
- options.SaveToken = true;
- Debug.Assert(settings.SecretKey != null, "settings.SecretKey != null");
- options.TokenValidationParameters = new TokenValidationParameters {
- ValidateIssuer = true,
- ValidateAudience = true,
- ValidateLifetime = true,
- ValidateIssuerSigningKey = true,
- ValidIssuer = settings.Issuer,
- ValidAudience = settings.Audience,
- IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.SecretKey)),
- ClockSkew = TimeSpan.Zero
- };
- // DISABLE THIS FOR PRODUCTION:
- options.IncludeErrorDetails = true;
- options.Events = new JwtBearerEvents {
- OnAuthenticationFailed = context => {
- var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
- logger.LogError($"Authentication failed. \n\tContext.Exception: '{context.Exception}'", context.Exception);
- return Task.CompletedTask;
- },
- OnChallenge = context => {
- var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
- logger.LogWarning($"OnChallenge error. \n\tcontext.Error: '{context.Error}'\n\tcontext.ErrorDescription: '{context.ErrorDescription}'", context.Error, context.ErrorDescription);
- return Task.CompletedTask;
- },
- OnMessageReceived = context => {
- var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
- logger.LogInformation("Message received: '{Token}'", context.Token);
- return Task.CompletedTask;
- },
- OnTokenValidated = context => {
- var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
- logger.LogInformation($"Token validated. \n\tcontext.SecurityToken: '{context.SecurityToken}'", context.SecurityToken);
- return Task.CompletedTask;
- }
- };
- });
- builder.Logging.ClearProviders();
- builder.Logging.AddConsole();
- builder.Logging.AddDebug();
- builder.Services.AddHttpContextAccessor();
- // Add services to the container.
- // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
- builder.Services.AddEndpointsApiExplorer();
- builder.Services.AddSwaggerGen(options => {
- options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme {
- In = ParameterLocation.Header,
- Name = "Authorization",
- Type = SecuritySchemeType.ApiKey
- });
- options.OperationFilter<SecurityRequirementsOperationFilter>();
- });
- Log.Logger = new LoggerConfiguration()
- .MinimumLevel.Information()
- .WriteTo.File("logs/general/api-logs-.txt", rollingInterval: RollingInterval.Day)
- // Configure Serilog for API endpoint logging
- .WriteTo.Logger(lc => lc
- .WriteTo.File("logs/endpoints/endpoint-logs-.txt", rollingInterval: RollingInterval.Day))
- .CreateLogger();
- builder.Logging.AddSerilog();
- return builder.Build();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement