diff --git a/.agents/skills/nitro/SKILL.md b/.agents/skills/nitro/SKILL.md index 4710849..e5aa0e1 100644 --- a/.agents/skills/nitro/SKILL.md +++ b/.agents/skills/nitro/SKILL.md @@ -22,7 +22,7 @@ metadata: 1. Run the app (`dotnet run --project ./src/Presentation`) or the compose file, and open Nitro. 2. Check the new field's description, arguments and nullability in the schema reference. They come from XML comments (`xml-docs-and-openapi`). 3. Run the happy path and the failure paths, and check the `extensions.code` of each error. -4. With authentication on, add an `Authorization: Bearer ` header in Nitro's connection settings. Introspection needs the token too, so the schema explorer stays empty until it's set, and `/graphql?sdl` is off (`security-defaults`). +4. With authentication on, add an `Authorization: Bearer ` header in Nitro's connection settings. For a local token, run `dotnet user-jwts create --project src/Presentation` (`optional-token-auth`). Introspection needs the token too, so the schema explorer stays empty until it's set, and `/graphql?sdl` is off (`security-defaults`). 5. Write the integration test as well (`presentation-integration-tests`). ## Don't 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 d5db5a7..1e9cc34 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -72,6 +72,20 @@ OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:7333 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 Nitro at , open the connection settings and add a header: `Authorization` with `Bearer `. The schema loads once the header is there. 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 15dc241..9a7340e 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 77ce760..7aea453 100644 --- a/src/Presentation/Extensions/ProgramExtensions.cs +++ b/src/Presentation/Extensions/ProgramExtensions.cs @@ -117,7 +117,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 2550157..c1f7cdf 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..d650f46 --- /dev/null +++ b/tests/Presentation.Tests.Integration/Authentication/DevelopmentTokenTests.cs @@ -0,0 +1,91 @@ +namespace CleanGraphQLApi.Presentation.Tests.Integration.Authentication; + +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text; +using System.Text.Json; +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 GraphQLApplication 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 Query_WithoutToken_ShouldReturn_NotAuthenticated() + { + // Arrange + using var client = this.application.CreateClient(); + + // Act + using var result = await Send(client); + + // Assert + result.RootElement.GetProperty("errors")[0].GetProperty("extensions").GetProperty("code").GetString().ShouldBe("AUTH_NOT_AUTHENTICATED"); + } + + [Fact] + public async Task Query_WithDevelopmentToken_ShouldReturn_Data() + { + // Arrange + using var client = this.application.CreateClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CreateToken(KeyBytes)); + + // Act + using var result = await Send(client); + + // Assert + result.RootElement.TryGetProperty("errors", out _).ShouldBeFalse(); + result.RootElement.GetProperty("data").GetProperty("version").GetProperty("fileVersion").GetString().ShouldNotBeNullOrWhiteSpace(); + } + + private static async Task Send(HttpClient client) + { + using var response = await client.PostAsync("/graphql", new { query = "{version{fileVersion}}" }.ToStringContent()); + + return JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + } + + 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 dafc577..a70a0a9 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"); + } }