|
1 | | -// ------------------------------------------------------------------------------------------------- |
| 1 | +// ------------------------------------------------------------------------------------------------- |
2 | 2 | // Copyright (c) Microsoft Corporation. All rights reserved. |
3 | 3 | // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. |
4 | 4 | // ------------------------------------------------------------------------------------------------- |
5 | 5 |
|
6 | | -using Microsoft.AspNetCore; |
7 | | -using Microsoft.AspNetCore.Hosting; |
| 6 | +using System; |
| 7 | +using System.Collections.Generic; |
| 8 | +using System.IdentityModel.Tokens.Jwt; |
| 9 | +using System.Net.Http; |
| 10 | +using System.Security.Cryptography.X509Certificates; |
| 11 | +using System.Text; |
| 12 | +using System.Threading.Tasks; |
| 13 | +using Microsoft.AspNetCore.Builder; |
| 14 | +using Microsoft.AspNetCore.Http; |
| 15 | +using Microsoft.Extensions.Configuration; |
| 16 | +using Microsoft.Extensions.DependencyInjection; |
| 17 | +using Microsoft.Health.Internal.SmartLauncher.Models; |
| 18 | +using Microsoft.IdentityModel.Tokens; |
| 19 | + |
| 20 | +var builder = WebApplication.CreateBuilder(args); |
| 21 | +builder.Services.AddHttpClient(); |
| 22 | + |
| 23 | +var app = builder.Build(); |
| 24 | +string cachedTokenEndpoint = null; |
| 25 | + |
| 26 | +app.UseDefaultFiles(); |
| 27 | +app.UseStaticFiles(); |
| 28 | + |
| 29 | +// GET /config — serves public configuration (no secrets) |
| 30 | +app.MapGet("/config", (IConfiguration configuration) => |
| 31 | +{ |
| 32 | + var config = new SmartLauncherConfig(); |
| 33 | + configuration.Bind(config); |
| 34 | + return Results.Ok(config); |
| 35 | +}); |
| 36 | + |
| 37 | +// POST /token-proxy — proxies token exchange for confidential clients |
| 38 | +app.MapPost("/token-proxy", async (HttpRequest request, IConfiguration configuration, IHttpClientFactory httpClientFactory) => |
| 39 | +{ |
| 40 | + var form = await request.ReadFormAsync(); |
| 41 | + var grantType = form["grant_type"].ToString(); |
| 42 | + var code = form["code"].ToString(); |
| 43 | + var redirectUri = form["redirect_uri"].ToString(); |
| 44 | + var codeVerifier = form["code_verifier"].ToString(); |
| 45 | + var clientId = configuration["ClientId"] ?? string.Empty; |
| 46 | + var clientType = configuration["ClientType"] ?? "public"; |
| 47 | + |
| 48 | + // Derive the token endpoint server-side from the configured FHIR server's |
| 49 | + // SMART configuration to prevent SSRF via a client-supplied URL. |
| 50 | + var fhirServerUrl = configuration["FhirServerUrl"]; |
| 51 | + if (string.IsNullOrEmpty(fhirServerUrl)) |
| 52 | + { |
| 53 | + return Results.BadRequest(new { error = "FhirServerUrl is not configured on the server." }); |
| 54 | + } |
| 55 | + |
| 56 | + string tokenEndpoint; |
| 57 | + try |
| 58 | + { |
| 59 | + if (string.IsNullOrEmpty(cachedTokenEndpoint)) |
| 60 | + { |
| 61 | + using var discoveryClient = httpClientFactory.CreateClient(); |
| 62 | + var smartConfigUrl = fhirServerUrl.TrimEnd('/') + "/.well-known/smart-configuration"; |
| 63 | + var smartResponse = await discoveryClient.GetAsync(new Uri(smartConfigUrl)); |
| 64 | + smartResponse.EnsureSuccessStatusCode(); |
| 65 | + var smartJson = await smartResponse.Content.ReadAsStringAsync(); |
| 66 | + var smartConfig = System.Text.Json.JsonDocument.Parse(smartJson); |
| 67 | + cachedTokenEndpoint = smartConfig.RootElement.GetProperty("token_endpoint").GetString() |
| 68 | + ?? throw new InvalidOperationException("token_endpoint not found in SMART configuration."); |
| 69 | + } |
| 70 | + |
| 71 | + tokenEndpoint = cachedTokenEndpoint; |
| 72 | + } |
| 73 | + catch (HttpRequestException ex) |
| 74 | + { |
| 75 | + return Results.Problem($"Failed to discover token endpoint from {fhirServerUrl}: {ex.Message}", statusCode: 502); |
| 76 | + } |
| 77 | + catch (System.Text.Json.JsonException ex) |
| 78 | + { |
| 79 | + return Results.Problem($"Failed to parse SMART configuration from {fhirServerUrl}: {ex.Message}", statusCode: 502); |
| 80 | + } |
| 81 | + catch (InvalidOperationException ex) |
| 82 | + { |
| 83 | + return Results.Problem($"Invalid SMART configuration from {fhirServerUrl}: {ex.Message}", statusCode: 502); |
| 84 | + } |
| 85 | + |
| 86 | + var tokenRequestParams = new Dictionary<string, string> |
| 87 | + { |
| 88 | + ["grant_type"] = grantType, |
| 89 | + ["code"] = code, |
| 90 | + ["redirect_uri"] = redirectUri, |
| 91 | + ["client_id"] = clientId, |
| 92 | + }; |
| 93 | + |
| 94 | + if (!string.IsNullOrEmpty(codeVerifier)) |
| 95 | + { |
| 96 | + tokenRequestParams["code_verifier"] = codeVerifier; |
| 97 | + } |
| 98 | + |
| 99 | + using var httpClient = httpClientFactory.CreateClient(); |
| 100 | + using var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenEndpoint) |
| 101 | + { |
| 102 | + Content = new FormUrlEncodedContent(tokenRequestParams), |
| 103 | + }; |
| 104 | + |
| 105 | + if (clientType.Equals("confidential-symmetric", StringComparison.OrdinalIgnoreCase)) |
| 106 | + { |
| 107 | + var clientSecret = configuration["ClientSecret"] ?? string.Empty; |
| 108 | + var credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}")); |
| 109 | + tokenRequest.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials); |
| 110 | + } |
| 111 | + else if (clientType.Equals("confidential-asymmetric", StringComparison.OrdinalIgnoreCase)) |
| 112 | + { |
| 113 | + var assertion = GenerateClientAssertion(clientId, tokenEndpoint, configuration); |
| 114 | + tokenRequestParams["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; |
| 115 | + tokenRequestParams["client_assertion"] = assertion; |
| 116 | + tokenRequest.Content = new FormUrlEncodedContent(tokenRequestParams); |
| 117 | + } |
| 118 | + |
| 119 | + var response = await httpClient.SendAsync(tokenRequest); |
| 120 | + var content = await response.Content.ReadAsStringAsync(); |
| 121 | + |
| 122 | + return Results.Content(content, "application/json", statusCode: (int)response.StatusCode); |
| 123 | +}); |
| 124 | + |
| 125 | +app.Run(); |
8 | 126 |
|
9 | | -namespace Microsoft.Health.Internal.SmartLauncher |
| 127 | +static string GenerateClientAssertion(string clientId, string tokenEndpoint, IConfiguration configuration) |
10 | 128 | { |
11 | | - internal static class Program |
| 129 | + X509Certificate2 cert = LoadCertificate(configuration); |
| 130 | + |
| 131 | + var securityKey = new X509SecurityKey(cert); |
| 132 | + var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256); |
| 133 | + |
| 134 | + var now = DateTime.UtcNow; |
| 135 | + var token = new JwtSecurityToken( |
| 136 | + issuer: clientId, |
| 137 | + audience: tokenEndpoint, |
| 138 | + claims: new[] |
| 139 | + { |
| 140 | + new System.Security.Claims.Claim("sub", clientId), |
| 141 | + new System.Security.Claims.Claim("jti", Guid.NewGuid().ToString()), |
| 142 | + }, |
| 143 | + notBefore: now, |
| 144 | + expires: now.AddMinutes(5), |
| 145 | + signingCredentials: signingCredentials); |
| 146 | + |
| 147 | + return new JwtSecurityTokenHandler().WriteToken(token); |
| 148 | +} |
| 149 | + |
| 150 | +static X509Certificate2 LoadCertificate(IConfiguration configuration) |
| 151 | +{ |
| 152 | + var certPath = configuration["CertificatePath"]; |
| 153 | + var certPassword = configuration["CertificatePassword"]; |
| 154 | + var certThumbprint = configuration["CertificateThumbprint"]; |
| 155 | + |
| 156 | + if (!string.IsNullOrEmpty(certPath)) |
| 157 | + { |
| 158 | +#pragma warning disable SYSLIB0057 // X509Certificate2 constructor is obsolete in .NET 9+ |
| 159 | + return new X509Certificate2(certPath, certPassword); |
| 160 | +#pragma warning restore SYSLIB0057 |
| 161 | + } |
| 162 | + |
| 163 | + if (!string.IsNullOrEmpty(certThumbprint)) |
12 | 164 | { |
13 | | - public static void Main(string[] args) |
| 165 | + using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); |
| 166 | + store.Open(OpenFlags.ReadOnly); |
| 167 | + var certs = store.Certificates.Find(X509FindType.FindByThumbprint, certThumbprint, validOnly: false); |
| 168 | + if (certs.Count == 0) |
14 | 169 | { |
15 | | - CreateWebHostBuilder(args).Build().Run(); |
| 170 | + throw new InvalidOperationException($"Certificate with thumbprint '{certThumbprint}' not found in CurrentUser\\My store."); |
16 | 171 | } |
17 | 172 |
|
18 | | - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => |
19 | | - WebHost.CreateDefaultBuilder(args) |
20 | | - .UseStartup<Startup>(); |
| 173 | + return certs[0]; |
21 | 174 | } |
| 175 | + |
| 176 | + throw new InvalidOperationException("No certificate configured. Set either CertificatePath or CertificateThumbprint in appsettings.json."); |
22 | 177 | } |
0 commit comments