diff --git a/src/DigitalData.Auth.API/Program.cs b/src/DigitalData.Auth.API/Program.cs index afaf3d8..2896576 100644 --- a/src/DigitalData.Auth.API/Program.cs +++ b/src/DigitalData.Auth.API/Program.cs @@ -17,24 +17,26 @@ using NLog.Web; var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger(); logger.Info("Logging initialized."); -var builder = WebApplication.CreateBuilder(args); +try +{ + var builder = WebApplication.CreateBuilder(args); -builder.Configuration.AddJsonFile("consumer-repository.json", true, true); + builder.Configuration.AddJsonFile("consumer-repository.json", true, true); -var config = builder.Configuration; + var config = builder.Configuration; -var apiParams = config.Get() ?? throw new InvalidOperationException("AuthApiOptions is missing or invalid in appsettings."); + var apiParams = config.Get() ?? throw new InvalidOperationException("AuthApiOptions is missing or invalid in appsettings."); -// Add services to the container. -builder.Services.Configure(config); -builder.Services.AddAuthService(config); -builder.Services.AddCryptoFactory(config.GetSection("CryptParams")); -builder.Services.AddJwtSignatureHandler(api => new Dictionary + // Add services to the container. + builder.Services.Configure(config); + builder.Services.AddAuthService(config); + builder.Services.AddCryptoFactory(config.GetSection("CryptParams")); + builder.Services.AddJwtSignatureHandler(api => new Dictionary { { JwtRegisteredClaimNames.Sub, api.Id }, { JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds() } }); -builder.Services.AddJwtSignatureHandler(user => new Dictionary + builder.Services.AddJwtSignatureHandler(user => new Dictionary { { JwtRegisteredClaimNames.Sub, user.Id }, { JwtRegisteredClaimNames.UniqueName, user.Username }, @@ -43,29 +45,29 @@ builder.Services.AddJwtSignatureHandler(user => new Dictionary -{ - options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme + builder.Services.AddEndpointsApiExplorer(); + builder.Services.AddSwaggerGen(options => { - Name = "Authorization", - Type = SecuritySchemeType.Http, - Scheme = "bearer", - BearerFormat = "JWT", - In = ParameterLocation.Header, - Description = "Enter 'Bearer' [space] and then your valid token." - }); + options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme + { + Name = "Authorization", + Type = SecuritySchemeType.Http, + Scheme = "bearer", + BearerFormat = "JWT", + In = ParameterLocation.Header, + Description = "Enter 'Bearer' [space] and then your valid token." + }); - options.AddSecurityRequirement(new OpenApiSecurityRequirement + options.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme @@ -82,69 +84,75 @@ builder.Services.AddSwaggerGen(options => new List() } }); -}); - -// Add authentication -Lazy? issuerSigningKeyInitiator = null; - -builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) - .AddJwtBearer(options => - { - options.RequireHttpsMetadata = apiParams!.RequireHttpsMetadata; - options.ClaimsIssuer = apiParams!.Issuer; - options.Audience = apiParams.LocalConsumer.Audience; - options.TokenValidationParameters = new() - { - ValidateIssuer = true, - ValidIssuer = apiParams!.Issuer, - ValidateAudience = true, - ValidAudience = apiParams.LocalConsumer.Audience, - ValidateLifetime = true, - IssuerSigningKey = issuerSigningKeyInitiator?.Value - }; - - options.Events = new JwtBearerEvents - { - OnMessageReceived = context => - { - // if there is no token read related cookie or query string - if (context.Token is null) // if there is no token - { - if (context.Request.Cookies.TryGetValue(apiParams!.DefaultCookieName, out var cookieToken) && cookieToken is not null) - context.Token = cookieToken; - else if (context.Request.Query.TryGetValue(apiParams.DefaultQueryStringKey, out var queryStrToken)) - context.Token = queryStrToken; - } - return Task.CompletedTask; - } - }; }); -var app = builder.Build(); + // Add authentication + Lazy? issuerSigningKeyInitiator = null; -issuerSigningKeyInitiator = new Lazy(() => -{ - var factory = app.Services.GetRequiredService(); - var desc = factory.TokenDescriptors.Get(apiParams.Issuer, apiParams.LocalConsumer.Audience); - return desc.Validator.SecurityKey; -}); + builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.RequireHttpsMetadata = apiParams!.RequireHttpsMetadata; + options.ClaimsIssuer = apiParams!.Issuer; + options.Audience = apiParams.LocalConsumer.Audience; + options.TokenValidationParameters = new() + { + ValidateIssuer = true, + ValidIssuer = apiParams!.Issuer, + ValidateAudience = true, + ValidAudience = apiParams.LocalConsumer.Audience, + ValidateLifetime = true, + IssuerSigningKey = issuerSigningKeyInitiator?.Value + }; -// Configure the HTTP request pipeline. -var use_swagger = config.GetValue("UseSwagger"); -if (app.Environment.IsDevelopment() || use_swagger) -{ - app.UseSwagger(); - app.UseSwaggerUI(); + options.Events = new JwtBearerEvents + { + OnMessageReceived = context => + { + // if there is no token read related cookie or query string + if (context.Token is null) // if there is no token + { + if (context.Request.Cookies.TryGetValue(apiParams!.DefaultCookieName, out var cookieToken) && cookieToken is not null) + context.Token = cookieToken; + else if (context.Request.Query.TryGetValue(apiParams.DefaultQueryStringKey, out var queryStrToken)) + context.Token = queryStrToken; + } + return Task.CompletedTask; + } + }; + }); + + var app = builder.Build(); + + issuerSigningKeyInitiator = new Lazy(() => + { + var factory = app.Services.GetRequiredService(); + var desc = factory.TokenDescriptors.Get(apiParams.Issuer, apiParams.LocalConsumer.Audience); + return desc.Validator.SecurityKey; + }); + + // Configure the HTTP request pipeline. + var use_swagger = config.GetValue("UseSwagger"); + if (app.Environment.IsDevelopment() || use_swagger) + { + app.UseSwagger(); + app.UseSwaggerUI(); + } + + app.UseHttpsRedirection(); + + app.UseAuthentication(); + + app.UseAuthorization(); + + app.MapControllers(); + + app.MapHub("/auth-hub"); + + app.Run(); } - -app.UseHttpsRedirection(); - -app.UseAuthentication(); - -app.UseAuthorization(); - -app.MapControllers(); - -app.MapHub("/auth-hub"); - -app.Run(); \ No newline at end of file +catch(Exception ex) +{ + logger.Error(ex, "Stopped program because of exception."); + throw; +} \ No newline at end of file