-
Notifications
You must be signed in to change notification settings - Fork 249
Add a console/worker app for certificate auth #391
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7bf2d8e
first pass on console app for certificate auth
TimHess 65d5d79
bump mem for auth apps on cf, adjust for runtime reverse proxy changes
TimHess 6a1866e
updates for reverse proxy changes, report full URI used on API requests
TimHess 28ee18d
PR feedback
TimHess 62d9492
address more feedback
TimHess 7d5f992
remove extra whitespace
TimHess File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| # DotNet | ||
| bin/ | ||
| obj/ | ||
| publish/ | ||
|
|
||
| # user-specific state | ||
| *.user | ||
|
|
||
| # VS Code | ||
| .vscode/ | ||
| *.code-workspace | ||
|
|
||
| # Visual Studio | ||
| .vs/ | ||
|
|
||
| # JetBrains | ||
| .idea/ | ||
| *.iws | ||
| *.iml | ||
| *.ipr | ||
|
|
||
| # Test framework files | ||
| scaffold/ | ||
| *.feature | ||
|
|
||
| # Common files that don't need to be pushed | ||
| config/ | ||
| *.http | ||
| manifest*.yml | ||
| *.md | ||
| launchSettings.json | ||
|
|
||
| # files specific this sample | ||
| GeneratedCertificates | ||
17 changes: 17 additions & 0 deletions
17
Security/src/AuthConsole/ApiClients/CertificateAuthorizationApiClient.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| using Steeltoe.Samples.AuthConsole.Models; | ||
|
|
||
| namespace Steeltoe.Samples.AuthConsole.ApiClients; | ||
|
|
||
| public sealed class CertificateAuthorizationApiClient(HttpClient httpClient) | ||
bart-vmware marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| : StringApiClient(httpClient) | ||
| { | ||
| public async Task<AuthApiResponseModel> GetSameOrgAsync(CancellationToken cancellationToken) | ||
| { | ||
| return await GetAsync("api/certificate/SameOrg", cancellationToken); | ||
| } | ||
|
|
||
| public async Task<AuthApiResponseModel> GetSameSpaceAsync(CancellationToken cancellationToken) | ||
| { | ||
| return await GetAsync("api/certificate/SameSpace", cancellationToken); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| using Steeltoe.Samples.AuthConsole.Models; | ||
|
|
||
| namespace Steeltoe.Samples.AuthConsole.ApiClients; | ||
|
|
||
| public abstract class StringApiClient(HttpClient httpClient) | ||
| { | ||
| protected HttpClient HttpClient => httpClient; | ||
|
|
||
| protected async Task<AuthApiResponseModel> GetAsync(string requestUri, CancellationToken cancellationToken) | ||
| { | ||
| string fullRequestUri = httpClient.BaseAddress + requestUri; | ||
|
|
||
| try | ||
| { | ||
| using HttpResponseMessage response = await httpClient.GetAsync(requestUri, cancellationToken); | ||
| string responseBody = await response.Content.ReadAsStringAsync(cancellationToken); | ||
|
|
||
| if (response.IsSuccessStatusCode) | ||
| { | ||
| return new AuthApiResponseModel | ||
| { | ||
| RequestUri = fullRequestUri, | ||
| Message = responseBody | ||
| }; | ||
| } | ||
|
|
||
| throw new HttpRequestException($"Request failed with status {(int)response.StatusCode}:{Environment.NewLine}{responseBody}"); | ||
| } | ||
| catch (Exception exception) | ||
| { | ||
| return new AuthApiResponseModel | ||
| { | ||
| RequestUri = fullRequestUri, | ||
| Error = exception | ||
| }; | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| namespace Steeltoe.Samples.AuthConsole; | ||
|
|
||
| internal sealed class CloudFoundryConventions | ||
| { | ||
| public const string ConfigurationPrefix = "CloudFoundryConventions"; | ||
|
|
||
| public string ApiUriSegment { get; set; } = ""; | ||
|
|
||
| public string AppsUriSegment { get; set; } = ""; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| <Project> | ||
| <PropertyGroup> | ||
| <SteeltoeVersion>4.0.*-*</SteeltoeVersion> | ||
| </PropertyGroup> | ||
| <PropertyGroup> | ||
| <AspNetCoreVersion>8.0.*</AspNetCoreVersion> | ||
| </PropertyGroup> | ||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| using Microsoft.Extensions.DependencyInjection.Extensions; | ||
| using Microsoft.Extensions.Http.Logging; | ||
|
|
||
| namespace Steeltoe.Samples.AuthConsole; | ||
|
|
||
| /// <summary> | ||
| /// Provides simplified logging of outgoing HTTP requests. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Based on https://josef.codes/customize-the-httpclient-logging-dotnet-core/. | ||
| /// </remarks> | ||
| public static class HttpClientBuilderExtensions | ||
| { | ||
| public static IHttpClientBuilder ConfigureLogging(this IHttpClientBuilder builder) | ||
| { | ||
| builder.Services.TryAddScoped<HttpLogger>(); | ||
| return builder.RemoveAllLoggers().AddLogger<HttpLogger>(true); | ||
| } | ||
|
|
||
| private sealed class HttpLogger(ILogger<HttpLogger> logger) : IHttpClientLogger | ||
| { | ||
| private readonly ILogger<HttpLogger> _logger = logger; | ||
|
|
||
| public object? LogRequestStart(HttpRequestMessage request) | ||
| { | ||
| _logger.LogInformation("Sending '{Request.Method}' to '{Request.Host}{Request.Path}'", request.Method, | ||
| request.RequestUri?.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped), request.RequestUri?.PathAndQuery); | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| public void LogRequestStop(object? context, HttpRequestMessage request, HttpResponseMessage response, TimeSpan elapsed) | ||
| { | ||
| _logger.LogInformation("Received '{Response.StatusCodeInt} {Response.StatusCodeString}' after {Response.ElapsedMilliseconds}ms", | ||
| (int)response.StatusCode, response.StatusCode, elapsed.TotalMilliseconds.ToString("F1")); | ||
| } | ||
|
|
||
| public void LogRequestFailed(object? context, HttpRequestMessage request, HttpResponseMessage? response, Exception exception, TimeSpan elapsed) | ||
| { | ||
| _logger.LogError(exception, "Request towards '{Request.Host}{Request.Path}' failed after {Response.ElapsedMilliseconds}ms", | ||
| request.RequestUri?.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped), request.RequestUri!.PathAndQuery, | ||
| elapsed.TotalMilliseconds.ToString("F1")); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| namespace Steeltoe.Samples.AuthConsole.Models; | ||
|
|
||
| public sealed class AuthApiResponseModel | ||
| { | ||
| public string? RequestUri { get; set; } | ||
| public string? Message { get; set; } | ||
| public Exception? Error { get; set; } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| using Microsoft.Extensions.Options; | ||
| using Steeltoe.Common; | ||
| using Steeltoe.Common.Certificates; | ||
| using Steeltoe.Configuration.CloudFoundry; | ||
| using Steeltoe.Samples.AuthConsole; | ||
| using Steeltoe.Samples.AuthConsole.ApiClients; | ||
| using Steeltoe.Security.Authorization.Certificate; | ||
|
|
||
| const string orgId = "a8fef16f-94c0-49e3-aa0b-ced7c3da6229"; | ||
| const string spaceId = "122b942a-d7b9-4839-b26e-836654b9785f"; | ||
|
|
||
| HostApplicationBuilder builder = Host.CreateApplicationBuilder(args); | ||
| builder.Services.AddHostedService<Worker>(); | ||
|
|
||
| // Steeltoe: Register IOptions that enable calculating the backend app's Uri based on the location of the Cloud Foundry API. | ||
| builder.Services.AddOptions<CloudFoundryConventions>().BindConfiguration(CloudFoundryConventions.ConfigurationPrefix); | ||
|
|
||
| // Steeltoe: Add Cloud Foundry application info and instance identity certificate to configuration. | ||
| builder.AddCloudFoundryConfiguration(); | ||
| builder.Configuration.AddAppInstanceIdentityCertificate(new Guid(orgId), new Guid(spaceId)); | ||
|
|
||
| // Steeltoe: register a typed HttpClient that includes the application instance identity certificate. | ||
| builder.Services.AddHttpClient<CertificateAuthorizationApiClient>(SetBaseAddress).AddAppInstanceIdentityCertificate().ConfigureLogging(); | ||
|
|
||
| IHost host = builder.Build(); | ||
| host.Run(); | ||
|
|
||
| return; | ||
|
|
||
| // This code is used to limit complexity in the sample. A real application should use Service Discovery. | ||
| // To learn more about service discovery, review the documentation at: https://docs.steeltoe.io/api/v4/discovery/ | ||
| static void SetBaseAddress(IServiceProvider serviceProvider, HttpClient client) | ||
| { | ||
| var instanceInfo = serviceProvider.GetRequiredService<IApplicationInstanceInfo>(); | ||
|
|
||
| if (instanceInfo is CloudFoundryApplicationOptions { Api: not null } options) | ||
| { | ||
| CloudFoundryConventions conventions = serviceProvider.GetRequiredService<IOptions<CloudFoundryConventions>>().Value; | ||
| string baseAddress = options.Api.Replace(conventions.ApiUriSegment, $"auth-server-sample.{conventions.AppsUriSegment}"); | ||
| client.BaseAddress = new Uri($"{baseAddress}"); | ||
| } | ||
| else | ||
| { | ||
| client.BaseAddress = new Uri("https://localhost:7184"); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| # Steeltoe Application Security Worker/Console Client-side Authentication and Authorization | ||
|
|
||
| This application shows how to use the Steeltoe [security library](https://docs.steeltoe.io/api/v4/security/) for authentication and authorization with client certificates provided by Cloud Foundry or Steeltoe (when running locally). | ||
|
|
||
| ## General pre-requisites | ||
|
|
||
| 1. Installed .NET 8 SDK | ||
| 1. Optional: [Tanzu Platform for Cloud Foundry](https://techdocs.broadcom.com/us/en/vmware-tanzu/platform/tanzu-platform-for-cloud-foundry/10-0/tpcf/concepts-overview.html) | ||
| (optionally with [Windows support](https://techdocs.broadcom.com/us/en/vmware-tanzu/platform/tanzu-platform-for-cloud-foundry/10-0/tpcf/toc-tasw-install-index.html)) | ||
| and [Cloud Foundry CLI](https://github.com/cloudfoundry/cli) | ||
|
|
||
| ## Running locally | ||
|
|
||
| 1. `dotnet run` both AuthApi and AuthConsole | ||
|
|
||
| ## Running on Tanzu Platform for Cloud Foundry | ||
|
|
||
| 1. Refer to the [AuthWeb README](../AuthWeb/README.md) for instructions on deploying AuthApi | ||
| * If you are only interested in certificate authentication, skip everything related to Single Sign-On (SSO) and comment out or delete the `sampleSSOService` service reference from manifest(-windows).yml before `cf push` | ||
|
|
||
| 1. Push AuthConsole to Cloud Foundry | ||
| 1. `cf target -o your-org -s your-space` | ||
| 1. `cd samples/Security/src/AuthConsole` | ||
| 1. `cf push` | ||
| * When deploying to Windows, binaries must be built locally before push. Use the following commands instead: | ||
|
|
||
| ```shell | ||
| dotnet publish -r win-x64 --self-contained | ||
| cf push -f manifest-windows.yml -p bin/Release/net8.0/win-x64/publish | ||
| ``` | ||
|
|
||
| > [!NOTE] | ||
| > The provided manifests will create apps named `auth-client-console-sample` and `auth-server-sample` | ||
| > and attempt to bind AuthApi to the SSO service `sampleSSOService`. | ||
|
|
||
| ## What to expect | ||
|
|
||
| At this point, the app is up and running. Since there is no user interface for this worker, you can access the logs with this command: `cf logs auth-client-console-sample` | ||
|
|
||
| --- | ||
|
|
||
| See the Official [Steeltoe Security Documentation](https://docs.steeltoe.io/api/v4/security/) for more detailed information. |
16 changes: 16 additions & 0 deletions
16
Security/src/AuthConsole/Steeltoe.Samples.AuthConsole.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Worker"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
bart-vmware marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| <Nullable>enable</Nullable> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Microsoft.Extensions.Hosting" Version="$(AspNetCoreVersion)" /> | ||
| <PackageReference Include="Steeltoe.Configuration.CloudFoundry" Version="$(SteeltoeVersion)" /> | ||
| <PackageReference Include="Steeltoe.Security.Authorization.Certificate" Version="$(SteeltoeVersion)" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| using Steeltoe.Samples.AuthConsole.ApiClients; | ||
| using Steeltoe.Samples.AuthConsole.Models; | ||
|
|
||
| namespace Steeltoe.Samples.AuthConsole; | ||
|
|
||
| public sealed class Worker(CertificateAuthorizationApiClient certificateAuthorizationApiClient, ILogger<Worker> logger) : BackgroundService | ||
| { | ||
| protected override async Task ExecuteAsync(CancellationToken cancellationToken) | ||
| { | ||
| while (!cancellationToken.IsCancellationRequested) | ||
| { | ||
| AuthApiResponseModel model = await certificateAuthorizationApiClient.GetSameOrgAsync(cancellationToken); | ||
| logger.LogInformation("Request Uri: {requestUri}", model.RequestUri); | ||
| logger.LogInformation("GetSameOrg response: {ApiResponse}", model.Message != null ? model.Message : model.Error); | ||
|
|
||
| model = await certificateAuthorizationApiClient.GetSameSpaceAsync(cancellationToken); | ||
| logger.LogInformation("Request Uri: {requestUri}", model.RequestUri); | ||
| logger.LogInformation("GetSameSpace response: {ApiResponse}", model.Message != null ? model.Message : model.Error); | ||
|
|
||
| Console.WriteLine("Sleeping for 10 seconds (press Ctrl+C to close)."); | ||
| await Task.Delay(10_000, cancellationToken); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| { | ||
| // Steeltoe: Add schema to get auto-completion. | ||
| "$schema": "https://steeltoe.io/schema/v4/schema.json", | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Warning", | ||
| "Microsoft.Hosting.Lifetime": "Information" | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| { | ||
| // Steeltoe: Add schema to get auto-completion. | ||
| "$schema": "https://steeltoe.io/schema/v4/schema.json", | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.Hosting.Lifetime": "Information" | ||
| } | ||
| }, | ||
| // Steeltoe: Identify the subdomains used in different areas of Cloud Foundry. | ||
| "CloudFoundryConventions": { | ||
bart-vmware marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| "ApiUriSegment": "api.sys", | ||
| "AppsUriSegment": "apps" | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| --- | ||
| applications: | ||
| - name: auth-client-console-sample | ||
| buildpacks: | ||
| - binary_buildpack | ||
| command: cmd /c .\Steeltoe.Samples.AuthConsole | ||
| health-check-type: process | ||
| memory: 128M | ||
| no-route: true | ||
| stack: windows | ||
| env: | ||
| DOTNET_CLI_TELEMETRY_OPTOUT: "true" | ||
| DOTNET_NOLOGO: "true" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.