|
1 | | -using App; |
2 | | - |
3 | | -var builder = WebApplication.CreateBuilder(args); |
4 | | - |
5 | | -builder.Services.AddHostedService<Worker>(); |
6 | | - |
7 | | -var app = builder.Build(); |
8 | | - |
9 | | -app.MapGet("/health", () => TypedResults.Ok()); |
10 | | - |
11 | | -app.Run(); |
| 1 | +using System.IdentityModel.Tokens.Jwt; |
| 2 | +using System.Net.Http.Headers; |
| 3 | +using System.Security.Claims; |
| 4 | +using System.Security.Cryptography; |
| 5 | +using System.Text; |
| 6 | +using System.Text.Json; |
| 7 | +using System.Text.Json.Serialization; |
| 8 | +using App; |
| 9 | +using Microsoft.IdentityModel.Tokens; |
| 10 | + |
| 11 | +var builder = WebApplication.CreateBuilder(args); |
| 12 | + |
| 13 | +builder.Services.AddHostedService<Worker>(); |
| 14 | +builder.Services.AddHttpClient(); |
| 15 | + |
| 16 | +var app = builder.Build(); |
| 17 | + |
| 18 | +app.MapGet("/health", () => TypedResults.Ok()); |
| 19 | + |
| 20 | +app.MapGet("/ttd/localtestapp/token", async (HttpContext context, IHttpClientFactory httpClientFactory, ILoggerFactory loggerFactory) => |
| 21 | +{ |
| 22 | + var logger = loggerFactory.CreateLogger("App"); |
| 23 | + logger.LogInformation("Received token request with scope: {scope}", context.Request.Query["scope"].ToString()); |
| 24 | + |
| 25 | + var scope = context.Request.Query["scope"].ToString(); |
| 26 | + if (string.IsNullOrEmpty(scope)) |
| 27 | + { |
| 28 | + return Results.Json(new { success = false, error = "Missing 'scope' query parameter" }); |
| 29 | + } |
| 30 | + |
| 31 | + try |
| 32 | + { |
| 33 | + // Read the maskinporten-settings.json from mounted secret |
| 34 | + const string secretPath = "/mnt/app-secrets/maskinporten-settings.json"; |
| 35 | + if (!File.Exists(secretPath)) |
| 36 | + { |
| 37 | + return Results.Json(new { success = false, error = $"Secret file not found at {secretPath}" }); |
| 38 | + } |
| 39 | + |
| 40 | + var settingsJson = await File.ReadAllTextAsync(secretPath); |
| 41 | + var settings = JsonSerializer.Deserialize<MaskinportenSettings>(settingsJson); |
| 42 | + if (settings == null) |
| 43 | + { |
| 44 | + return Results.Json(new { success = false, error = "Failed to deserialize settings" }); |
| 45 | + } |
| 46 | + |
| 47 | + if (string.IsNullOrEmpty(settings.ClientId)) |
| 48 | + { |
| 49 | + return Results.Json(new { success = false, error = "ClientId is empty in settings" }); |
| 50 | + } |
| 51 | + |
| 52 | + if (settings.Jwk == null) |
| 53 | + { |
| 54 | + return Results.Json(new { success = false, error = "JWK is null in settings" }); |
| 55 | + } |
| 56 | + |
| 57 | + // Create RSA key from JWK |
| 58 | + var rsa = RSA.Create(); |
| 59 | + var rsaParams = new RSAParameters |
| 60 | + { |
| 61 | + Modulus = Base64UrlDecode(settings.Jwk.N), |
| 62 | + Exponent = Base64UrlDecode(settings.Jwk.E), |
| 63 | + D = Base64UrlDecode(settings.Jwk.D), |
| 64 | + P = Base64UrlDecode(settings.Jwk.P), |
| 65 | + Q = Base64UrlDecode(settings.Jwk.Q), |
| 66 | + DP = Base64UrlDecode(settings.Jwk.Dp), |
| 67 | + DQ = Base64UrlDecode(settings.Jwk.Dq), |
| 68 | + InverseQ = Base64UrlDecode(settings.Jwk.Qi) |
| 69 | + }; |
| 70 | + rsa.ImportParameters(rsaParams); |
| 71 | + |
| 72 | + var securityKey = new RsaSecurityKey(rsa) { KeyId = settings.Jwk.Kid }; |
| 73 | + var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256); |
| 74 | + |
| 75 | + // Create JWT assertion |
| 76 | + var now = DateTime.UtcNow; |
| 77 | + var claims = new[] |
| 78 | + { |
| 79 | + new Claim("scope", scope), |
| 80 | + new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) |
| 81 | + }; |
| 82 | + |
| 83 | + var tokenDescriptor = new SecurityTokenDescriptor |
| 84 | + { |
| 85 | + Subject = new ClaimsIdentity(claims), |
| 86 | + Issuer = settings.ClientId, |
| 87 | + Audience = settings.Authority, |
| 88 | + Expires = now.AddSeconds(60), |
| 89 | + IssuedAt = now, |
| 90 | + NotBefore = now, |
| 91 | + SigningCredentials = credentials |
| 92 | + }; |
| 93 | + |
| 94 | + var tokenHandler = new JwtSecurityTokenHandler(); |
| 95 | + var jwtToken = tokenHandler.CreateToken(tokenDescriptor); |
| 96 | + var assertion = tokenHandler.WriteToken(jwtToken); |
| 97 | + |
| 98 | + // Call the Maskinporten token endpoint |
| 99 | + var httpClient = httpClientFactory.CreateClient(); |
| 100 | + var tokenUrl = $"http://fakes.runtime-operator.svc.cluster.local:8050/token?grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion={Uri.EscapeDataString(assertion)}"; |
| 101 | + |
| 102 | + var response = await httpClient.PostAsync(tokenUrl, null); |
| 103 | + var responseContent = await response.Content.ReadAsStringAsync(); |
| 104 | + |
| 105 | + if (!response.IsSuccessStatusCode) |
| 106 | + { |
| 107 | + return Results.Json(new { success = false, error = $"Token endpoint returned {response.StatusCode}: {responseContent}" }); |
| 108 | + } |
| 109 | + |
| 110 | + var tokenResponse = JsonSerializer.Deserialize<TokenResponse>(responseContent); |
| 111 | + if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.AccessToken)) |
| 112 | + { |
| 113 | + return Results.Json(new { success = false, error = "Failed to parse token response" }); |
| 114 | + } |
| 115 | + |
| 116 | + // Decode the access token (it's base64-encoded JSON in the fake) |
| 117 | + var decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(tokenResponse.AccessToken)); |
| 118 | + var tokenClaims = JsonSerializer.Deserialize<FakeTokenClaims>(decodedToken); |
| 119 | + |
| 120 | + return Results.Json(new |
| 121 | + { |
| 122 | + success = true, |
| 123 | + claims = tokenClaims |
| 124 | + }); |
| 125 | + } |
| 126 | + catch (Exception ex) |
| 127 | + { |
| 128 | + return Results.Json(new { success = false, error = ex.Message }); |
| 129 | + } |
| 130 | +}); |
| 131 | + |
| 132 | +app.Run(); |
| 133 | + |
| 134 | +static byte[] Base64UrlDecode(string? input) |
| 135 | +{ |
| 136 | + if (string.IsNullOrEmpty(input)) |
| 137 | + return Array.Empty<byte>(); |
| 138 | + |
| 139 | + // Convert base64url to base64 |
| 140 | + var base64 = input.Replace('-', '+').Replace('_', '/'); |
| 141 | + switch (base64.Length % 4) |
| 142 | + { |
| 143 | + case 2: base64 += "=="; break; |
| 144 | + case 3: base64 += "="; break; |
| 145 | + } |
| 146 | + return Convert.FromBase64String(base64); |
| 147 | +} |
| 148 | + |
| 149 | +public class MaskinportenSettings |
| 150 | +{ |
| 151 | + [JsonPropertyName("clientId")] |
| 152 | + public string? ClientId { get; set; } |
| 153 | + |
| 154 | + [JsonPropertyName("authority")] |
| 155 | + public string? Authority { get; set; } |
| 156 | + |
| 157 | + [JsonPropertyName("jwk")] |
| 158 | + public JwkKey? Jwk { get; set; } |
| 159 | +} |
| 160 | + |
| 161 | +public class JwkKey |
| 162 | +{ |
| 163 | + [JsonPropertyName("kty")] |
| 164 | + public string? Kty { get; set; } |
| 165 | + |
| 166 | + [JsonPropertyName("kid")] |
| 167 | + public string? Kid { get; set; } |
| 168 | + |
| 169 | + [JsonPropertyName("n")] |
| 170 | + public string? N { get; set; } |
| 171 | + |
| 172 | + [JsonPropertyName("e")] |
| 173 | + public string? E { get; set; } |
| 174 | + |
| 175 | + [JsonPropertyName("d")] |
| 176 | + public string? D { get; set; } |
| 177 | + |
| 178 | + [JsonPropertyName("p")] |
| 179 | + public string? P { get; set; } |
| 180 | + |
| 181 | + [JsonPropertyName("q")] |
| 182 | + public string? Q { get; set; } |
| 183 | + |
| 184 | + [JsonPropertyName("dp")] |
| 185 | + public string? Dp { get; set; } |
| 186 | + |
| 187 | + [JsonPropertyName("dq")] |
| 188 | + public string? Dq { get; set; } |
| 189 | + |
| 190 | + [JsonPropertyName("qi")] |
| 191 | + public string? Qi { get; set; } |
| 192 | +} |
| 193 | + |
| 194 | +public class TokenResponse |
| 195 | +{ |
| 196 | + [JsonPropertyName("access_token")] |
| 197 | + public string? AccessToken { get; set; } |
| 198 | + |
| 199 | + [JsonPropertyName("token_type")] |
| 200 | + public string? TokenType { get; set; } |
| 201 | + |
| 202 | + [JsonPropertyName("scope")] |
| 203 | + public string? Scope { get; set; } |
| 204 | + |
| 205 | + [JsonPropertyName("expires_in")] |
| 206 | + public int ExpiresIn { get; set; } |
| 207 | +} |
| 208 | + |
| 209 | +public class FakeTokenClaims |
| 210 | +{ |
| 211 | + [JsonPropertyName("scopes")] |
| 212 | + public string[]? Scopes { get; set; } |
| 213 | + |
| 214 | + [JsonPropertyName("client_id")] |
| 215 | + public string? ClientId { get; set; } |
| 216 | +} |
0 commit comments