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
50 changes: 50 additions & 0 deletions .github/workflows/test-dotnet.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
name: Test .NET Frameworks

on:
push:
paths:
- "samples/**"
pull_request:
paths:
- "samples/**"
schedule:
- cron: "0 8 * * 1"
workflow_dispatch:

permissions:
contents: read

jobs:
find-projects:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.find.outputs.matrix }}
steps:
- uses: actions/checkout@v6
- id: find
run: |
DIRS=$(find samples -name "*.sln" -not -path "*/node_modules/*" -exec dirname {} \; 2>/dev/null | sort | jq -R -s -c 'split("\n") | map(select(. != ""))')
echo "matrix=$DIRS" >> "$GITHUB_OUTPUT"

test:
needs: find-projects
if: ${{ needs.find-projects.outputs.matrix != '[]' }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
project: ${{ fromJson(needs.find-projects.outputs.matrix) }}
steps:
- uses: actions/checkout@v6
- uses: actions/setup-dotnet@v4
with:
dotnet-version: "10.0.x"
- name: Restore
working-directory: ${{ matrix.project }}
run: dotnet restore
- name: Build
working-directory: ${{ matrix.project }}
run: dotnet build --no-restore --configuration Release
- name: Test
working-directory: ${{ matrix.project }}
run: dotnet test --no-build --configuration Release
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,8 @@ Thumbs.db

# Design docs (kept local)
docs/

# .NET build artifacts
bin/
obj/
*.user
14 changes: 14 additions & 0 deletions placeholder-map.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,17 @@ ts:
placeholder: "{{POST_LOGOUT_URI}}"
- pattern: "process.env.SCOPES"
placeholder: "{{SCOPES}}"

csharp:
- pattern: 'RequireEnv("ISSUER_URL")'
placeholder: "{{ISSUER_URL}}"
- pattern: 'RequireEnv("CLIENT_ID")'
placeholder: "{{CLIENT_ID}}"
- pattern: 'RequireEnv("CLIENT_SECRET")'
placeholder: "{{CLIENT_SECRET}}"
- pattern: 'RequireEnv("REDIRECT_URI")'
placeholder: "{{REDIRECT_URI}}"
- pattern: 'RequireEnv("POST_LOGOUT_URI")'
placeholder: "{{POST_LOGOUT_URI}}"
- pattern: 'RequireEnv("SCOPES")'
placeholder: "{{SCOPES}}"
11 changes: 11 additions & 0 deletions samples/dotnet/login-auth-code/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
CLIENT_ID=your-client-id
CLIENT_SECRET=your-client-secret
ISSUER_URL=https://your-tenant.us.connect.secureauth.com/your-workspace
Comment thread
ksroda-sa marked this conversation as resolved.
SCOPES=openid profile email

# These are for configuring your SecureAuth application registration.
# The sample derives the callback/logout paths from the OIDC middleware's
# default options (CallbackPath = "/callback", SignedOutCallbackPath =
# "/signout-callback-oidc"), so it doesn't read these at runtime.
REDIRECT_URI=https://localhost:4260/callback
POST_LOGOUT_URI=https://localhost:4260/signout-callback-oidc
37 changes: 37 additions & 0 deletions samples/dotnet/login-auth-code/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# .NET — Server Login with Auth Code + PKCE

Minimal ASP.NET Core 10 Minimal-APIs app demonstrating server-side OIDC login using `Microsoft.AspNetCore.Authentication.OpenIdConnect`. The server holds the client secret and manages the session via an encrypted auth cookie.

## Prerequisites

- .NET 10 SDK installed (`dotnet --version` → 10.x)
- `dotnet dev-certs https --trust` — run once per machine to trust the local dev HTTPS cert
- A SecureAuth application configured as a **confidential server app** (client type `server_web`, with a client secret)

## Setup

1. Copy `.env.example` to `.env` and fill in your SecureAuth values (including `CLIENT_SECRET`)
2. `dotnet restore`
3. `dotnet run --project src`
4. Open https://localhost:4260

## What this demonstrates

- OIDC discovery via `AddOpenIdConnect(options => { options.Authority = ... })`
- Authorization Code + PKCE flow (middleware handles code exchange, state validation, PKCE verifier)
- Session carried by an encrypted auth cookie (protected by ASP.NET Core data protection). With `SaveTokens = true` the ID token is serialized into that cookie — no opaque tokens appear in the browser UI, but the cookie itself is a client-stored artifact.
- RP-initiated logout via `Results.SignOut(...)` on Cookie + OIDC schemes

## Tests

```
dotnet test
```

Covers the four non-library code paths: `/` unauthenticated, `/` authenticated (via fake auth scheme), `/login` challenge, `/logout` sign-out.

## Production notes

- Replace the dev cert with a real TLS certificate (via a reverse proxy or configured Kestrel endpoint).
- ASP.NET Core's data-protection keys default to in-memory in dev. In production, configure a persistent key ring (filesystem / blob / Redis) so auth cookies survive restarts and work across instances.
- Consider scoping auth middleware to protected routes only via `[Authorize]` attributes or `RequireAuthorization()`.
30 changes: 30 additions & 0 deletions samples/dotnet/login-auth-code/login-auth-code.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "login-auth-code", "src\login-auth-code.csproj", "{78EB9BB4-218C-40E2-97DF-0A5EB467F957}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "login-auth-code.tests", "tests\login-auth-code.tests.csproj", "{1F9DCFBA-4FB4-4806-A98A-A186DD115179}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{78EB9BB4-218C-40E2-97DF-0A5EB467F957}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{78EB9BB4-218C-40E2-97DF-0A5EB467F957}.Debug|Any CPU.Build.0 = Debug|Any CPU
{78EB9BB4-218C-40E2-97DF-0A5EB467F957}.Release|Any CPU.ActiveCfg = Release|Any CPU
{78EB9BB4-218C-40E2-97DF-0A5EB467F957}.Release|Any CPU.Build.0 = Release|Any CPU
{1F9DCFBA-4FB4-4806-A98A-A186DD115179}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1F9DCFBA-4FB4-4806-A98A-A186DD115179}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1F9DCFBA-4FB4-4806-A98A-A186DD115179}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1F9DCFBA-4FB4-4806-A98A-A186DD115179}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C3B3262A-0EC4-405A-9AAF-D2CFB28EB9A6}
EndGlobalSection
EndGlobal
108 changes: 108 additions & 0 deletions samples/dotnet/login-auth-code/src/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using DotNetEnv;

// @snippet:step1:start
// @description Load environment variables from .env (searches parent dirs so `dotnet run --project src` finds the .env at the sample root). Existing env vars win.
Env.TraversePath().NoClobber().Load();
// @snippet:step1:end

var builder = WebApplication.CreateBuilder(args);

// @snippet:step2:start
// @description Configure cookie auth + OpenID Connect against your SecureAuth workspace
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = RequireEnv("ISSUER_URL");
options.ClientId = RequireEnv("CLIENT_ID");
options.ClientSecret = RequireEnv("CLIENT_SECRET");
options.ResponseType = "code";
options.UsePkce = true;
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
// Keep OIDC claim names (given_name, family_name, email) as-is — the
// default middleware remaps them to long xmlsoap URIs, which makes
// FindFirst("given_name") return null in user code.
options.MapInboundClaims = false;
options.CallbackPath = "/callback";
options.Scope.Clear();
foreach (var scope in RequireEnv("SCOPES").Split(' ', StringSplitOptions.RemoveEmptyEntries))
options.Scope.Add(scope);
});

static string RequireEnv(string name) =>
Environment.GetEnvironmentVariable(name)
?? throw new InvalidOperationException($"Missing required env var: {name}");

builder.Services.AddAuthorization();
// @snippet:step2:end

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

// @snippet:step3:start
// @description Wire routes for sign-in redirect, user display, and sign-out
app.MapGet("/", (HttpContext ctx) =>
ctx.User.Identity?.IsAuthenticated == true
? Results.Content(Views.RenderSignedInPage(ctx.User), "text/html")
: Results.Content(Views.RenderSignedOutPage(), "text/html"));

app.MapGet("/login", () => Results.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
[OpenIdConnectDefaults.AuthenticationScheme]));

app.MapGet("/logout", () => Results.SignOut(
new AuthenticationProperties { RedirectUri = "/" },
[CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme]));
// @snippet:step3:end

app.Run("https://localhost:4260");

public partial class Program { }

static class Views
{
public static string RenderSignedOutPage() => """
<!doctype html>
<html><head><title>SecureAuth .NET Auth Code Demo</title></head>
<body>
<h1>SecureAuth .NET Auth Code Demo</h1>
<p><a href="/login">Sign in</a></p>
</body></html>
""";

public static string RenderSignedInPage(ClaimsPrincipal user)
{
var given = Escape(user.FindFirst("given_name")?.Value ?? "");
var family = Escape(user.FindFirst("family_name")?.Value ?? "");
var email = Escape(user.FindFirst("email")?.Value ?? "");
var fullName = $"{given} {family}".Trim();
var name = string.IsNullOrWhiteSpace(fullName) ? "there" : fullName;
var emailSuffix = email.Length > 0 ? $" ({email})" : "";
return $"""
<!doctype html>
<html><head><title>SecureAuth .NET Auth Code Demo</title></head>
<body>
<h1>SecureAuth .NET Auth Code Demo</h1>
<p>Welcome, {name}{emailSuffix}</p>
<p><a href="/logout">Sign out</a></p>
</body></html>
""";
}

static string Escape(string s) => s
.Replace("&", "&amp;")
.Replace("<", "&lt;")
.Replace(">", "&gt;")
.Replace("\"", "&quot;")
.Replace("'", "&#39;");
}
13 changes: 13 additions & 0 deletions samples/dotnet/login-auth-code/src/login-auth-code.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>login-auth-code</AssemblyName>
<RootNamespace>LoginAuthCode</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="10.0.0" />
<PackageReference Include="DotNetEnv" Version="3.1.1" />
</ItemGroup>
</Project>
115 changes: 115 additions & 0 deletions samples/dotnet/login-auth-code/tests/AuthIntegrationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
using System.Net;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Xunit;

namespace LoginAuthCode.Tests;

public class AuthIntegrationTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;

public AuthIntegrationTests(WebApplicationFactory<Program> factory)
{
// Env vars needed by the sample app so the OIDC middleware initializes at app boot time.
Environment.SetEnvironmentVariable("ISSUER_URL", "https://idp.example");
Environment.SetEnvironmentVariable("CLIENT_ID", "test-client");
Environment.SetEnvironmentVariable("CLIENT_SECRET", "test-secret");
Environment.SetEnvironmentVariable("SCOPES", "openid profile email");

_factory = factory.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
// Pre-populate OIDC Configuration so the middleware doesn't call the
// discovery endpoint (which would fail — there's no real IdP here).
services.Configure<OpenIdConnectOptions>(
OpenIdConnectDefaults.AuthenticationScheme,
options =>
{
options.Configuration = new OpenIdConnectConfiguration
{
Issuer = "https://idp.example",
AuthorizationEndpoint = "https://idp.example/authorize",
TokenEndpoint = "https://idp.example/token",
EndSessionEndpoint = "https://idp.example/end_session",
JwksUri = "https://idp.example/jwks",
};
});
});
});
}

[Fact]
public async Task Root_Unauthenticated_ShowsSignIn()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
});
var res = await client.GetAsync("/");
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var body = await res.Content.ReadAsStringAsync();
Assert.Contains("Sign in", body);
}

[Fact]
public async Task Root_Authenticated_ShowsWelcome()
{
var factory = _factory.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.AddAuthentication("Test")
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", _ => { });
services.PostConfigure<AuthenticationOptions>(options =>
{
options.DefaultScheme = "Test";
options.DefaultAuthenticateScheme = "Test";
});
});
});
var client = factory.CreateClient();
var res = await client.GetAsync("/");
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var body = await res.Content.ReadAsStringAsync();
Assert.Contains("Welcome, Test User (test@example.com)", body);
}

[Fact]
public async Task Login_ReturnsChallengeRedirectToAuthorizeEndpoint()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
});
var res = await client.GetAsync("/login");
Assert.True(
res.StatusCode == HttpStatusCode.Redirect || res.StatusCode == HttpStatusCode.Found,
$"Expected redirect, got {res.StatusCode}");
var location = res.Headers.Location!.ToString();
Assert.Contains("idp.example/authorize", location);
Assert.Contains("client_id=test-client", location);
Assert.Contains("response_type=code", location);
Assert.Contains("code_challenge=", location);
}

[Fact]
public async Task Logout_RedirectsToEndSessionEndpoint()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
});
var res = await client.GetAsync("/logout");
Assert.True(
res.StatusCode == HttpStatusCode.Redirect || res.StatusCode == HttpStatusCode.Found,
$"Expected redirect, got {res.StatusCode}");
var location = res.Headers.Location!.ToString();
Assert.Contains("idp.example/end_session", location);
}
}
Loading
Loading