diff --git a/VagrantBoxUploader/VagrantBoxUploader/Dockerfile b/VagrantBoxUploader/VagrantBoxUploader/Dockerfile new file mode 100644 index 0000000..94a8277 --- /dev/null +++ b/VagrantBoxUploader/VagrantBoxUploader/Dockerfile @@ -0,0 +1,30 @@ +# See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging. + +# This stage is used when running from VS in fast mode (Default for Debug configuration) +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base +USER $APP_UID +WORKDIR /app +EXPOSE 8080 +EXPOSE 8081 + + +# This stage is used to build the service project +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build +ARG BUILD_CONFIGURATION=Release +WORKDIR /src +COPY ["VagrantBoxUploader/VagrantBoxUploader.csproj", "VagrantBoxUploader/"] +RUN dotnet restore "./VagrantBoxUploader/VagrantBoxUploader.csproj" +COPY . . +WORKDIR "/src/VagrantBoxUploader" +RUN dotnet build "./VagrantBoxUploader.csproj" -c $BUILD_CONFIGURATION -o /app/build + +# This stage is used to publish the service project to be copied to the final stage +FROM build AS publish +ARG BUILD_CONFIGURATION=Release +RUN dotnet publish "./VagrantBoxUploader.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false + +# This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration) +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "VagrantBoxUploader.dll"] \ No newline at end of file diff --git a/VagrantBoxUploader/VagrantBoxUploader/Models/UploadViewModel.cs b/VagrantBoxUploader/VagrantBoxUploader/Models/UploadViewMod.cs similarity index 100% rename from VagrantBoxUploader/VagrantBoxUploader/Models/UploadViewModel.cs rename to VagrantBoxUploader/VagrantBoxUploader/Models/UploadViewMod.cs diff --git a/VagrantBoxUploader/VagrantBoxUploader/OpenIDConnect/OpenIDConnectUtils.cs b/VagrantBoxUploader/VagrantBoxUploader/OpenIDConnect/OpenIDConnectUtils.cs new file mode 100644 index 0000000..aad7d59 --- /dev/null +++ b/VagrantBoxUploader/VagrantBoxUploader/OpenIDConnect/OpenIDConnectUtils.cs @@ -0,0 +1,161 @@ +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authentication.OpenIdConnect; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.IdentityModel.Tokens; +using System.IdentityModel.Tokens.Jwt; +using System.Text; + + +// Required NuGet Packages +// Microsoft.AspNetCore.Authentication.JwtBearer +// Microsoft.AspNetCore.Authentication.OpenIdConnect +// Microsoft.IdentityModel.Protocols.OpenIdConnect +// Microsoft.AspNet.WebApi.Core + +namespace VagrantBoxUploader.OpenIDConnect +{ + public class OpenIDConnectUtils + { + // Configuration priority from highest to lowest + // Highest: Command line arguments + // : Non-prefixed environment variables + // : User secrets from the .NET User Secrets Manager + // : Any appsettings.{ ENVIRONMENT_NAME }.json files + // : The appsettings.json file + // Lowest : Fallback to the host configuration + + /// + /// Setting up OpenIDConnect authentication (Program.cs) + /// + /// WebApplicationBuilder + + public void ConfigureBuild(WebApplicationBuilder builder) + { + // Add services to the container. + MyConfiguration.Set(builder.Configuration); + builder.Services.AddAuthentication(options => + { + options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; + }) + .AddCookie() + .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options => + { + options.Authority = builder.Configuration["OpenIDRealmURI"]; + options.ClientId = builder.Configuration["OpenIDClient"]; + options.ClientSecret = builder.Configuration["OpenIDSecret"]; + options.CallbackPath = "/signin-oidc"; + + // Authorization Code flow (recommended) + options.ResponseType = "code"; + options.SaveTokens = true; // store tokens in auth properties + options.GetClaimsFromUserInfoEndpoint = true; + options.MapInboundClaims = false; + + // Scopes - clear then add what's needed + options.Scope.Clear(); + options.Scope.Add("openid"); + options.Scope.Add("profile"); + options.Scope.Add("ucn"); + options.Scope.Add("email"); + options.Scope.Add("offline_access"); // to get refresh tokens + + // Map claim types if needed + options.TokenValidationParameters = new TokenValidationParameters + { + RoleClaimType = "roles", // 👈 IMPORTANT + NameClaimType = "name", + ValidateIssuer = true, + ValidateAudience = true + }; + + options.MapInboundClaims = false; // prevent automatic claim type mapping + options.RequireHttpsMetadata = true; // set to false only for development + + // Optional: events for logging / error handling + options.Events = new OpenIdConnectEvents + { + OnTokenValidated = context => + { + // e.g. add custom claims or logging + var loggerFactory = context.HttpContext.RequestServices.GetRequiredService(); + var logger = loggerFactory.CreateLogger("Api.Authorization"); + var claims = context?.Principal?.Claims; + if (claims is null || !claims.Any()) + { + logger.LogWarning("Claims null or empty"); + return Task.CompletedTask; + } + var claimsBuilder = new StringBuilder(); + claimsBuilder.AppendLine("User Claims:"); + foreach (var claim in claims) + { + claimsBuilder.AppendLine($"[{claim.Type}] - [{claim.Value}]"); + } + logger.LogTrace("{Claims}", claimsBuilder.ToString()); + return Task.CompletedTask; + }, + OnAuthenticationFailed = context => + { + context.HandleResponse(); + context.Response.Redirect("/Error?message=" + Uri.EscapeDataString(context.Exception.Message)); + return Task.CompletedTask; + } + }; + }); + // Change here for authorization policies + builder.Services + .AddAuthorizationBuilder() + .AddPolicy("read_access", builder => + { + // claim, list of acceptable values + builder.RequireClaim("myClaim", "MyClaimValueRO1", "MyClaimValueRO2"); + }) + .AddPolicy("write_access", builder => + { + builder.RequireClaim("myClaim", "MyClaimValueRW1", "MyClaimValueRW2"); + }); + // Require authentication globally (optional) + builder.Services.AddRazorPages(options => + { + options.Conventions.AuthorizeFolder("/"); + }); + builder.Services.Configure(options => + { + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; + options.KnownNetworks.Clear(); + options.KnownProxies.Clear(); + }); + + } + + + public JwtSecurityToken GetJwtPayload(HttpContext myContext) + { + var handler = new JwtSecurityTokenHandler(); + return handler.ReadJwtToken(myContext.GetTokenAsync("access_token").Result); + } + + public string GetJwtClaim(HttpContext myContext, string theClaim) + { + JwtSecurityToken jwtPayload = GetJwtPayload(myContext); + return jwtPayload.Claims.FirstOrDefault(claim => claim.Type == theClaim).Value; + } + } + + static public class MyConfiguration + { + static ConfigurationManager _config; + static public void Set(ConfigurationManager config) + { + _config = config; + } + + static public ConfigurationManager Get() + { + return _config; + } + + } +} diff --git a/VagrantBoxUploader/VagrantBoxUploader/Pages/Shared/_Layout.cshtml b/VagrantBoxUploader/VagrantBoxUploader/Pages/Shared/_Layout.cshtml index a4533a9..93491de 100644 --- a/VagrantBoxUploader/VagrantBoxUploader/Pages/Shared/_Layout.cshtml +++ b/VagrantBoxUploader/VagrantBoxUploader/Pages/Shared/_Layout.cshtml @@ -39,7 +39,7 @@
- © 2026 - VagrantBoxUploader - Privacy + © 2025 - VagrantBoxUploader - Privacy
diff --git a/VagrantBoxUploader/VagrantBoxUploader/Program.cs b/VagrantBoxUploader/VagrantBoxUploader/Program.cs index d32372f..dae71e7 100644 --- a/VagrantBoxUploader/VagrantBoxUploader/Program.cs +++ b/VagrantBoxUploader/VagrantBoxUploader/Program.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Http.Features; using VagrantBoxUploader.Services; +using VagrantBoxUploader.OpenIDConnect; var builder = WebApplication.CreateBuilder(args); @@ -23,6 +24,9 @@ builder.WebHost.ConfigureKestrel(options => 7L * 1024 * 1024 * 1024; // 7 GB }); +// Configure for OpenID +OpenIDConnectUtils oidcConfig = new(); +oidcConfig.ConfigureBuild(builder); var app = builder.Build(); @@ -30,12 +34,16 @@ var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); + // 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(); app.UseRouting(); +app.UseForwardedHeaders(); +app.UseAuthentication(); app.UseAuthorization(); - app.MapStaticAssets(); app.MapRazorPages() .WithStaticAssets(); diff --git a/VagrantBoxUploader/VagrantBoxUploader/Properties/launchSettings.json b/VagrantBoxUploader/VagrantBoxUploader/Properties/launchSettings.json index 41f7a21..95fe12d 100644 --- a/VagrantBoxUploader/VagrantBoxUploader/Properties/launchSettings.json +++ b/VagrantBoxUploader/VagrantBoxUploader/Properties/launchSettings.json @@ -1,14 +1,34 @@ { - "$schema": "https://json.schemastore.org/launchsettings.json", "profiles": { "http": { "commandName": "Project", - "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "http://localhost:5062", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" - } + }, + "dotnetRunMessages": true, + "applicationUrl": "http://localhost:5233" + }, + "https": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": true, + "applicationUrl": "https://localhost:7777" + }, + "Container (Dockerfile)": { + "commandName": "Docker", + "launchBrowser": true, + "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}", + "environmentVariables": { + "ASPNETCORE_HTTPS_PORTS": "8081", + "ASPNETCORE_HTTP_PORTS": "8080" + }, + "publishAllPorts": true, + "useSSL": true } - } -} + }, + "$schema": "https://json.schemastore.org/launchsettings.json" +} \ No newline at end of file diff --git a/VagrantBoxUploader/VagrantBoxUploader/VagrantBoxUploader.csproj b/VagrantBoxUploader/VagrantBoxUploader/VagrantBoxUploader.csproj index 474d608..f0aafa3 100644 --- a/VagrantBoxUploader/VagrantBoxUploader/VagrantBoxUploader.csproj +++ b/VagrantBoxUploader/VagrantBoxUploader/VagrantBoxUploader.csproj @@ -4,6 +4,15 @@ net10.0 enable enable + 779b8593-a90f-4ced-8735-24defdc472f2 + Linux + + + + + + + diff --git a/VagrantBoxUploader/VagrantBoxUploader/appsettings.json b/VagrantBoxUploader/VagrantBoxUploader/appsettings.json index 014a4b0..54e7972 100644 --- a/VagrantBoxUploader/VagrantBoxUploader/appsettings.json +++ b/VagrantBoxUploader/VagrantBoxUploader/appsettings.json @@ -2,11 +2,18 @@ "Logging": { "LogLevel": { "Default": "Information", - "Microsoft.AspNetCore": "Warning" + "Microsoft.AspNetCore": "Warning", + "Microsoft.AspNetCore.Authentication": "Information", + "Microsoft.AspNetCore.Authorization": "Information", + "Api.Authorization": "Trace" } }, "AllowedHosts": "*", "Gitea": { "DefaultBaseUri": "https://gitea.a.ucnit.eu" - } + }, + "Comment3": "Arguments for KeyCloak Code Flow", + "OpenIDRealmURI": "https://auth.a.ucnit.eu/realms/UCNit", + "OpenIDClient": "General", + "OpenIDSecret": "7mIerwlVkhOX6wWYIWMzh3qiJq8pm1dn" }