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/nitro/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <token>` 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 <token>` 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
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 @@ -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.

<!--#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 Nitro at <https://localhost:7331/graphql>, open the connection settings and add a header: `Authorization` with `Bearer <token>`. 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.

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

The app redirects HTTP to HTTPS whenever it has an HTTPS port, which is why `dotnet run` sends <http://localhost:7330> on to <https://localhost:7331>. 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;
}
}
4 changes: 3 additions & 1 deletion src/Presentation/Extensions/ProgramExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
});
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,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<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 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<JsonDocument> 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)
});
}
}
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