Skip to content
Closed
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
2 changes: 1 addition & 1 deletion .agents/skills/openapi-and-scalar/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ The OpenAPI document is generated at runtime by `Microsoft.AspNetCore.OpenApi` a
| Transformer | Adds |
| --- | --- |
| `DocumentInfoTransformer` | Title (with the environment name), description, contact, licence, external docs and the tag descriptions |
| `BearerSecurityTransformer` | Only in a solution with authentication, and only when `Authentication:Authority` is set: the `Bearer` security scheme, a security requirement and a `401` response on every operation that needs a token |
| `BearerSecurityTransformer` | Only in a solution with authentication, and only when `Authentication:Authority` or `dotnet user-jwts` is set up: the `Bearer` security scheme, a security requirement and a `401` response on every operation that needs a token |

Scalar is set up in `WebApplicationExtensions.ConfigureApplication` with the title, C# `HttpClient` as the default code sample, and its developer tools, agent, MCP and telemetry features turned off.

Expand Down
4 changes: 3 additions & 1 deletion .agents/skills/optional-token-auth/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ Authentication is a choice made when the solution is created. With `--include-au

With `--include-auth`, endpoints always ask for authorization. An empty `Authentication:Authority` still runs everything open, because the default policy then lets every request through, which is how the tests run unless they set an authority. Only health checks and the API reference (where a template has them) are anonymous. The version endpoint is protected like everything else; telemetry carries `service.version` for anyone who needs to know what's deployed. The Lambda template has no token authentication; API Gateway or the caller's IAM role does that job.

Settings are read through `AuthenticationSettings.FromConfiguration` (`Enabled` is true when the authority isn't empty).
Settings are read through `AuthenticationSettings.FromConfiguration`. `Enabled` is true when the authority isn't empty or `dotnet user-jwts` is set up.

For a token on a developer's machine, `dotnet user-jwts create --project src/Presentation` writes `Authentication:Schemes:Bearer` (issuer and audiences) into `appsettings.Development.json` and the signing key into user secrets. When that issuer is there, `UsesDevelopmentTokens` is true and wins over the authority: the JWT bearer handler gets no authority and reads the issuer, audiences and key from that section by itself. Both files only load in `Development`, so deployed copies keep using the authority. `DevelopmentTokenTests` sets the same keys in memory and signs a token with them.

Open is only fine on a developer's machine. In the web templates, with or without `--include-auth`, `DeploymentGuard` stops a deployed environment (anything but `Development` and `docker`) starting without authentication unless `Authentication:AllowAnonymous` is `true`, and checks that a set authority is an `https` URL (`security-defaults`).

Expand Down
14 changes: 14 additions & 0 deletions docs/RUN.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,20 @@ OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:7313 dotnet run --project ./src/Pre

Every span, metric and log carries `service.version`, so you can always tell which build sent it.

<!--#if (includeAuth) -->
## Trying it with a token

With an authority set, every call needs a token from it. To try the app on your machine without one, let .NET make you a development token:

```bash
dotnet user-jwts create --project src/Presentation
```

It prints a token, adds a `UserSecretsId` to the project, keeps the signing key in your user secrets and writes the issuer and audiences into `appsettings.Development.json`. From then on a `dotnet run` accepts its tokens instead of your authority's. Nothing changes anywhere else, because user secrets and that file only load in `Development`.

In Scalar at <https://localhost:7311/scalar>, open **Authentication**, choose the `Bearer` scheme and paste the token. In `Presentation.http`, set `@token` and uncomment the `Authorization` lines. Run `dotnet user-jwts create` again for a fresh token, and `dotnet user-jwts clear --project src/Presentation` and delete the `Authentication` block from `appsettings.Development.json` to go back to your authority.

<!--#endif -->
## HTTPS

The app redirects HTTP to HTTPS whenever it has an HTTPS port, which is why `dotnet run` sends <http://localhost:7310> on to <https://localhost:7311>. Outside the `Development` environment it also sends an HSTS header. The container only listens on HTTP, so in production put it behind a proxy or load balancer that ends TLS, and set `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true` so the app knows the original request was HTTPS.
Expand Down
23 changes: 21 additions & 2 deletions src/Presentation/Authentication/AuthenticationSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,29 @@ public class AuthenticationSettings
/// <summary>The audience access tokens must be issued for. This is usually the API's own URL.</summary>
public string? Audience { get; init; }

public bool Enabled => !string.IsNullOrWhiteSpace(this.Authority);
/// <summary>
/// The issuer <c>dotnet user-jwts</c> writes to <c>appsettings.Development.json</c>, read from
/// <c>Authentication:Schemes:Bearer:ValidIssuer</c>. When it's set, the app accepts the tokens that tool creates.
/// </summary>
public string? DevelopmentTokenIssuer { get; private set; }

/// <summary>Whether requests need a token: true when an authority or <c>dotnet user-jwts</c> is set up.</summary>
public bool Enabled => !string.IsNullOrWhiteSpace(this.Authority) || this.UsesDevelopmentTokens;

/// <summary>
/// Whether the tokens come from <c>dotnet user-jwts</c>. They win over the authority, so running the tool switches
/// a <c>dotnet run</c> to them and clearing it switches back.
/// </summary>
public bool UsesDevelopmentTokens => !string.IsNullOrWhiteSpace(this.DevelopmentTokenIssuer);

/// <summary>Whether a real authorization server issues the tokens.</summary>
public bool HasAuthority => !string.IsNullOrWhiteSpace(this.Authority) && !this.UsesDevelopmentTokens;

public static AuthenticationSettings FromConfiguration(IConfiguration configuration)
{
return configuration.GetSection(SectionName).Get<AuthenticationSettings>() ?? new AuthenticationSettings();
var settings = configuration.GetSection(SectionName).Get<AuthenticationSettings>() ?? new AuthenticationSettings();
settings.DevelopmentTokenIssuer = configuration[$"{SectionName}:Schemes:Bearer:ValidIssuer"];

return settings;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,9 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = authentication.Authority;
// With dotnet user-jwts set up, there's no authority to ask: the tool has put the issuer, audiences
// and signing key in the settings, and the handler reads them from Authentication:Schemes:Bearer.
options.Authority = authentication.HasAuthority ? authentication.Authority : null;
options.Audience = authentication.Audience;
options.MapInboundClaims = false;
});
Expand Down
3 changes: 2 additions & 1 deletion src/Presentation/Security/DeploymentGuard.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ public static void EnsureSafeToStart(IHostEnvironment environment, IConfiguratio

if (authentication.Enabled)
{
if (!Uri.TryCreate(authentication.Authority, UriKind.Absolute, out var authority) || authority.Scheme != Uri.UriSchemeHttps)
if (!string.IsNullOrWhiteSpace(authentication.Authority) &&
(!Uri.TryCreate(authentication.Authority, UriKind.Absolute, out var authority) || authority.Scheme != Uri.UriSchemeHttps))
{
throw new InvalidOperationException(
$"Authentication:Authority must be an absolute https URL, such as https://login.example.com, not '{authentication.Authority}'.");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
namespace CleanMinimalApi.Presentation.Tests.Integration.Authentication;

using System.Net;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using Shouldly;
using Xunit;

public class DevelopmentTokenTests : IDisposable
{
private const string Issuer = "dotnet-user-jwts";
private const string Audience = "http://localhost";

private static readonly byte[] KeyBytes = Encoding.UTF8.GetBytes("a-development-signing-key-for-the-tests-1234");

// What dotnet user-jwts writes: the issuer and audiences in appsettings.Development.json, the key in user secrets.
private readonly MinimalApiApplication application = new(settings: new Dictionary<string, string?>
{
["Authentication:Schemes:Bearer:ValidIssuer"] = Issuer,
["Authentication:Schemes:Bearer:ValidAudiences:0"] = Audience,
["Authentication:Schemes:Bearer:SigningKeys:0:Id"] = "test",
["Authentication:Schemes:Bearer:SigningKeys:0:Issuer"] = Issuer,
["Authentication:Schemes:Bearer:SigningKeys:0:Value"] = Convert.ToBase64String(KeyBytes),
["Authentication:Schemes:Bearer:SigningKeys:0:Length"] = "32"
});

[Fact]
public async Task Request_WithoutToken_ShouldReturn_Unauthorized()
{
// Arrange
using var client = this.application.CreateClient();

// Act
using var response = await client.GetAsync(new Uri("/api/movies", UriKind.Relative));

// Assert
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}

[Fact]
public async Task Request_WithDevelopmentToken_ShouldReturn_Ok()
{
// Arrange
using var client = this.application.CreateClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CreateToken(KeyBytes));

// Act
using var response = await client.GetAsync(new Uri("/api/movies", UriKind.Relative));

// Assert
response.StatusCode.ShouldBe(HttpStatusCode.OK);
}

[Fact]
public async Task Request_WithTokenSignedByAnotherKey_ShouldReturn_Unauthorized()
{
// Arrange
using var client = this.application.CreateClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CreateToken(Encoding.UTF8.GetBytes("someone-elses-signing-key-that-is-long-enough")));

// Act
using var response = await client.GetAsync(new Uri("/api/movies", UriKind.Relative));

// Assert
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}

public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.application.Dispose();
}
}

private static string CreateToken(byte[] key)
{
return new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor
{
Issuer = Issuer,
Audience = Audience,
Subject = new ClaimsIdentity([new Claim("sub", "developer")]),
Expires = DateTime.UtcNow.AddMinutes(5),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,26 @@ public void FromConfiguration_ShouldReturn_EnabledSettings_WhenAuthorityIsSet()
result.Authority.ShouldBe("https://login.example.com");
result.Audience.ShouldBe("https://api.example.com");
}

[Fact]
public void FromConfiguration_ShouldReturn_EnabledSettings_WhenDevelopmentTokensAreSetUp_EvenWithAnAuthority()
{
// Arrange
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["Authentication:Authority"] = "https://login.example.com",
["Authentication:Schemes:Bearer:ValidIssuer"] = "dotnet-user-jwts"
})
.Build();

// Act
var result = AuthenticationSettings.FromConfiguration(configuration);

// Assert
result.Enabled.ShouldBeTrue();
result.UsesDevelopmentTokens.ShouldBeTrue();
result.HasAuthority.ShouldBeFalse();
result.DevelopmentTokenIssuer.ShouldBe("dotnet-user-jwts");
}
}
Loading