diff --git a/.agents/skills/openapi-and-scalar/SKILL.md b/.agents/skills/openapi-and-scalar/SKILL.md index b352695..893eeb2 100644 --- a/.agents/skills/openapi-and-scalar/SKILL.md +++ b/.agents/skills/openapi-and-scalar/SKILL.md @@ -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 `ProgramExtensions.ConfigureApplication` with the title, C# `HttpClient` as the default code sample, and its developer tools, agent, MCP and telemetry features turned off. diff --git a/.agents/skills/optional-token-auth/SKILL.md b/.agents/skills/optional-token-auth/SKILL.md index a750d70..93a43d5 100644 --- a/.agents/skills/optional-token-auth/SKILL.md +++ b/.agents/skills/optional-token-auth/SKILL.md @@ -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`). diff --git a/docs/RUN.md b/docs/RUN.md index 1593daf..8a85c9b 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -73,6 +73,20 @@ OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:7343 dotnet run --project ./src/Pre Every span, metric and log carries `service.version`, so you can always tell which build sent it. + +## 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 , 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. + + ## HTTPS The app redirects HTTP to HTTPS whenever it has an HTTPS port, which is why `dotnet run` sends on to . 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. diff --git a/src/Presentation/Authentication/AuthenticationSettings.cs b/src/Presentation/Authentication/AuthenticationSettings.cs index 953f412..caad9e8 100644 --- a/src/Presentation/Authentication/AuthenticationSettings.cs +++ b/src/Presentation/Authentication/AuthenticationSettings.cs @@ -15,10 +15,29 @@ public class AuthenticationSettings /// The audience access tokens must be issued for. This is usually the API's own URL. public string? Audience { get; init; } - public bool Enabled => !string.IsNullOrWhiteSpace(this.Authority); + /// + /// The issuer dotnet user-jwts writes to appsettings.Development.json, read from + /// Authentication:Schemes:Bearer:ValidIssuer. When it's set, the app accepts the tokens that tool creates. + /// + public string? DevelopmentTokenIssuer { get; private set; } + + /// Whether requests need a token: true when an authority or dotnet user-jwts is set up. + public bool Enabled => !string.IsNullOrWhiteSpace(this.Authority) || this.UsesDevelopmentTokens; + + /// + /// Whether the tokens come from dotnet user-jwts. They win over the authority, so running the tool switches + /// a dotnet run to them and clearing it switches back. + /// + public bool UsesDevelopmentTokens => !string.IsNullOrWhiteSpace(this.DevelopmentTokenIssuer); + + /// Whether a real authorization server issues the tokens. + public bool HasAuthority => !string.IsNullOrWhiteSpace(this.Authority) && !this.UsesDevelopmentTokens; public static AuthenticationSettings FromConfiguration(IConfiguration configuration) { - return configuration.GetSection(SectionName).Get() ?? new AuthenticationSettings(); + var settings = configuration.GetSection(SectionName).Get() ?? new AuthenticationSettings(); + settings.DevelopmentTokenIssuer = configuration[$"{SectionName}:Schemes:Bearer:ValidIssuer"]; + + return settings; } } diff --git a/src/Presentation/Extensions/ProgramExtensions.cs b/src/Presentation/Extensions/ProgramExtensions.cs index 201e9a6..72de9e2 100644 --- a/src/Presentation/Extensions/ProgramExtensions.cs +++ b/src/Presentation/Extensions/ProgramExtensions.cs @@ -149,7 +149,9 @@ public static WebApplicationBuilder ConfigureBuilder(this WebApplicationBuilder .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; }); diff --git a/src/Presentation/Security/DeploymentGuard.cs b/src/Presentation/Security/DeploymentGuard.cs index f34f82d..89e3834 100644 --- a/src/Presentation/Security/DeploymentGuard.cs +++ b/src/Presentation/Security/DeploymentGuard.cs @@ -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}'."); diff --git a/tests/Presentation.Tests.Integration/Authentication/DevelopmentTokenTests.cs b/tests/Presentation.Tests.Integration/Authentication/DevelopmentTokenTests.cs new file mode 100644 index 0000000..0fda0ff --- /dev/null +++ b/tests/Presentation.Tests.Integration/Authentication/DevelopmentTokenTests.cs @@ -0,0 +1,97 @@ +namespace CleanWebApi.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 WebApiApplication application = new(settings: new Dictionary + { + ["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) + }); + } +} diff --git a/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs b/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs index c5674f2..5def158 100644 --- a/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs +++ b/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs @@ -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 + { + ["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"); + } }