diff --git a/Groceries/Program.cs b/Groceries/Program.cs index 3eb058f..84a6d82 100644 --- a/Groceries/Program.cs +++ b/Groceries/Program.cs @@ -1,7 +1,9 @@ using DbUp; using Groceries.Common; using Groceries.Data; +using Microsoft.AspNetCore.Authentication.OAuth; using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.EntityFrameworkCore; @@ -37,7 +39,29 @@ if (env.IsProduction()) dataProtection.PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(dataDir, "keys"))); } -var mvc = builder.Services +var oauthConfig = builder.Configuration.GetSection("OAuth"); +if (oauthConfig.Exists()) +{ + const string authenticationScheme = "OAuth"; + builder.Services.Configure(authenticationScheme, oauthConfig); + + builder.Services + .AddAuthentication(options => + { + options.DefaultScheme = IdentityConstants.ExternalScheme; + options.DefaultChallengeScheme = authenticationScheme; + }) + .AddOAuth(authenticationScheme, options => + { + options.SignInScheme = IdentityConstants.ExternalScheme; + options.CallbackPath = "/signin"; + }) + .AddExternalCookie(); + + builder.Services.AddAuthorization(); +} + +builder.Services .AddControllersWithViews() .AddRazorOptions(options => { @@ -63,10 +87,21 @@ var app = builder.Build(); app.UseStaticFiles(); app.UseRouting(); + +if (oauthConfig.Exists()) +{ + app.UseAuthentication(); + app.UseAuthorization(); +} + app.UseSession(); -app.MapControllers(); +var controllers = app.MapControllers(); +if (oauthConfig.Exists()) +{ + controllers.RequireAuthorization(); +} -app.Run(); +await app.RunAsync(); return 0; diff --git a/Groceries/config.ini b/Groceries/config.ini index c87eddf..a83ec50 100644 --- a/Groceries/config.ini +++ b/Groceries/config.ini @@ -1,5 +1,12 @@ -Database="Host=127.0.0.1;Username=groceries;Password=password;Database=groceries" +Database = "Host=127.0.0.1;Username=groceries;Password=password;Database=groceries" [Logging:LogLevel] -Default=Information -Microsoft=Warning +Default = Information +Microsoft = Warning + +[OAuth] +;AuthorizationEndpoint = +;TokenEndpoint = +;ClientId = +;ClientSecret = +;UsePkce = false