Compare commits

...
3 Commits
Author SHA1 Message Date
Karsten Jeppesen e588d3ae82 workflow update
CICD-UCN/VagrantBoxUploader/pipeline/head This commit looks good
2026-11-25 09:06:12 +01:00
Karsten Jeppesen 01437e2c6e Authentication active
CICD-UCN/VagrantBoxUploader/pipeline/head This commit looks good
2026-10-23 07:25:11 +02:00
Karsten Jeppesen 18fee408d1 Added authentication 2026-10-22 15:00:16 +02:00
12 changed files with 272 additions and 24 deletions
+7
View File
@@ -1,6 +1,13 @@
#!/bin/bash
echo "OK" > jenkins.result
# Check dotnet10 installed
! which dotnet || sudo apt-get install -y dotnet10
if ! which dotnet; then
echo "DOTNET NOT FOUND"
exit 1
fi
# Find all .csproj files and loop through them
find . -type f -name "*.csproj" | while read -r csproj; do
echo "Building $csproj..."
+1
View File
@@ -56,6 +56,7 @@ pipeline {
stage('Change to unix files') {
steps {
echo "Change to unix files"
sh "! which dos2unix || sudo apt-get install -y dos2unix"
sh "/bin/dos2unix .workflow/* .workflow/*"
sh "/bin/chmod +x .workflow/* .workflow/*"
}
+12 -11
View File
@@ -1,20 +1,21 @@
Jenkinsfile with AI provisions
The Build Agent should provide the following environment (in alphabetical order):
- GITEA_AGENT in clear text
- GITEA_API_URL https://gitea.a.ucnit.eu/api/v1 in clear text
- GITEA_API_KEY 046xxxxxxxxxxf76 in clear text
- GITEA_AGENT in clear text cicd-builder
- GITEA_API_URL in clear text https://gitea.a.ucnit.eu/api/v1
- GITEA_API_KEY in clear text
- GIT_USER in clear text
- MAX_FILE_BYTES 20000 in clear text
- OLLAMA_API_KEY sk-b5844exxxxx01 in clear text
- OLLAMA_API_URI https://ollama.a.ucnit.eu/ollama/v1 in clear text
- OLLAMA_MODEL llama3.1:8b in clear text
- REQUEST_TIMEOUT_SEC 3600 in clear text
- FILE_EXTS cshtml,cs,js,json in clear text
- MAX_FILE_BYTES in clear text
- OLLAMA_API_KEY through credentials:secret text
- OLLAMA_API_URI in clear text https://agent:12tf56so@ollama-api.a.ucnit.eu/v1
- OLLAMA_MODEL in clear text
- REQUEST_TIMEOUT_SEC through credentials:secret text
- FILE_EXTS in clear text (cshtml,cs,js,json)
And the following settings
- Remote root directory ./jenkins
- Remote root directory ~/jenkins
- Labels builder
- Launch method Launch agents via ssh
- Host Key Verification Strategy Not verifying
\ No newline at end of file
@@ -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"]
@@ -13,7 +13,7 @@ namespace VagrantBoxUploader.Models
public string BaseUri { get; set; } = string.Empty;
[Required]
[Display(Name = "Gitea user name")]
[Display(Name = "Gitea Organization name")]
public string Username { get; set; } = string.Empty;
[Required]
@@ -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
/// <summary>
/// Setting up OpenIDConnect authentication (Program.cs)
/// </summary>
/// <param name="builder">WebApplicationBuilder</param>
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<ILoggerFactory>();
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<ForwardedHeadersOptions>(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;
}
}
}
@@ -1,3 +1,4 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using VagrantBoxUploader.Models;
@@ -5,6 +6,7 @@ using VagrantBoxUploader.Services;
namespace VagrantBoxUploader.Pages;
public class IndexModel : PageModel
{
private readonly GiteaPackageService _giteaService;
@@ -25,6 +27,7 @@ public class IndexModel : PageModel
public bool UploadSucceeded { get; set; }
[Authorize]
public void OnGet()
{
Upload.BaseUri =
@@ -34,6 +37,7 @@ public class IndexModel : PageModel
Upload.Provider = "virtualbox";
}
[Authorize]
public async Task<IActionResult> OnPostAsync(
CancellationToken cancellationToken)
{
@@ -39,7 +39,7 @@
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2026 - VagrantBoxUploader - <a asp-area="" asp-page="/Privacy">Privacy</a>
&copy; 2025 - VagrantBoxUploader - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>
@@ -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();
@@ -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"
}
@@ -4,6 +4,15 @@
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>779b8593-a90f-4ced-8735-24defdc472f2</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.11" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="10.0.11" />
<PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="8.22.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
</ItemGroup>
</Project>
@@ -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"
}