Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions Security/src/AuthApi/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Steeltoe.Common.Certificates;
using Steeltoe.Configuration.CloudFoundry;
using Steeltoe.Configuration.CloudFoundry.ServiceBindings;
Expand Down Expand Up @@ -27,7 +26,7 @@
builder.Configuration.AddAppInstanceIdentityCertificate(new Guid(orgId), new Guid(spaceId));

// Steeltoe: Register Microsoft's JWT Bearer and Certificate libraries for authentication, configure JWT to work with UAA/Cloud Foundry.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer().ConfigureJwtBearerForCloudFoundry().AddCertificate();
builder.Services.AddAuthentication().AddJwtBearer().ConfigureJwtBearerForCloudFoundry().AddCertificate();

// Steeltoe: Register Microsoft authorization services.
builder.Services.AddAuthorizationBuilder()
Expand Down
2 changes: 1 addition & 1 deletion Security/src/AuthApi/Steeltoe.Samples.AuthApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions Security/src/AuthApi/manifest-windows.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
---
---
applications:
- name: auth-server-sample
buildpacks:
- binary_buildpack
command: cmd /c .\Steeltoe.Samples.AuthApi --urls=http://0.0.0.0:%PORT%
memory: 128M
memory: 256M
stack: windows
env:
DOTNET_CLI_TELEMETRY_OPTOUT: "true"
Expand Down
4 changes: 2 additions & 2 deletions Security/src/AuthApi/manifest.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
---
---
applications:
- name: auth-server-sample
buildpacks:
- dotnet_core_buildpack
memory: 128M
memory: 256M
stack: cflinuxfs4
env:
DOTNET_CLI_TELEMETRY_OPTOUT: "true"
Expand Down
34 changes: 34 additions & 0 deletions Security/src/AuthConsole/.cfignore
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
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)
: 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);
}
}
38 changes: 38 additions & 0 deletions Security/src/AuthConsole/ApiClients/StringApiClient.cs
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
};
}
}
}
10 changes: 10 additions & 0 deletions Security/src/AuthConsole/CloudFoundryConventions.cs
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; } = "";
}
8 changes: 8 additions & 0 deletions Security/src/AuthConsole/Directory.Build.props
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>
45 changes: 45 additions & 0 deletions Security/src/AuthConsole/HttpClientBuilderExtensions.cs
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"));
}
}
}
8 changes: 8 additions & 0 deletions Security/src/AuthConsole/Models/AuthApiResponseModel.cs
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; }
}
46 changes: 46 additions & 0 deletions Security/src/AuthConsole/Program.cs
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");
}
}
42 changes: 42 additions & 0 deletions Security/src/AuthConsole/README.md
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 Security/src/AuthConsole/Steeltoe.Samples.AuthConsole.csproj
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>
<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>
24 changes: 24 additions & 0 deletions Security/src/AuthConsole/Worker.cs
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);
}
}
}
10 changes: 10 additions & 0 deletions Security/src/AuthConsole/appsettings.Development.json
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"
}
}
}
15 changes: 15 additions & 0 deletions Security/src/AuthConsole/appsettings.json
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": {
"ApiUriSegment": "api.sys",
"AppsUriSegment": "apps"
}
}
13 changes: 13 additions & 0 deletions Security/src/AuthConsole/manifest-windows.yml
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"
Loading
Loading