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
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ You can configure token expiration in [`appsettings.json`](/src/Server/Boilerpla
"Identity": {
"BearerTokenExpiration": "0.00:05:00", // Format: D.HH:mm:ss (5 minutes)
"RefreshTokenExpiration": "14.00:00:00", // 14 days
"JwtIssuerSigningKeySecret": "VeryLongJWTIssuerSigningKeySecretThatIsMoreThan64BytesToEnsureCompatibilityWithHS512Algorithm"
}
```

Expand Down Expand Up @@ -470,7 +469,6 @@ public class AppClaimTypes

```json
"Identity": {
"JwtIssuerSigningKeySecret": "VeryLongJWTIssuerSigningKeySecretThatIsMoreThan64BytesToEnsureCompatibilityWithHS512Algorithm",
"Issuer": "Boilerplate",
"Audience": "Boilerplate",
"BearerTokenExpiration": "0.00:05:00",
Expand Down Expand Up @@ -701,54 +699,6 @@ Let's walk through a password reset scenario:

## Advanced Topics

### JWT Token Signing with PFX Certificates

By default, the Bit Boilerplate uses a string-based secret (`JwtIssuerSigningKeySecret`) for signing JWT tokens in the [`AppJwtSecureDataFormat`](/src/Server/Boilerplate.Server.Api/Features/Identity/Services/AppJwtSecureDataFormat.cs) class. While this approach is valid and secure, using a **PFX certificate** is considered best practice for production environments, especially when:

- You need to share JWT validation across multiple backend services
- You want to follow industry-standard cryptographic practices
- You're deploying to enterprise environments with strict security requirements

**Why We Didn't Use PFX by Default**

We chose the string-based secret as the default because:
- **Easier Deployment**: PFX certificates require additional configuration on shared hosting providers
- **Simplified Development**: Developers can get started immediately without certificate management
- **Good Security**: String-based secrets with HS512 are still cryptographically secure

**How to Migrate to PFX Certificates**

If you want to use PFX certificates, you'll need to modify [`AppJwtSecureDataFormat`](/src/Server/Boilerplate.Server.Api/Features/Identity/Services/AppJwtSecureDataFormat.cs) to use `AsymmetricSecurityKey` instead of `SymmetricSecurityKey`:

```csharp
// Instead of:
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.Identity.JwtIssuerSigningKeySecret))

// Use:
var certificate = new X509Certificate2("path/to/certificate.pfx", "password");
IssuerSigningKey = new X509SecurityKey(certificate)
```

**Protecting ASP.NET Core Data Protection Keys**

Additionally, you should protect the Data Protection keys stored in the database. In [`Program.Services.cs`](/src/Server/Boilerplate.Server.Api/Program.Services.cs), update the following code:

```csharp
services.AddDataProtection()
.PersistKeysToDbContext<AppDbContext>()
.ProtectKeysWithCertificate(certificate); // Add this line
```

**Cross-Service JWT Validation**

When using PFX certificates, you can share the **public key** with other backend services to validate JWTs issued by your ASP.NET Core Identity system. Other services can use the `AddJwtAuthentication` method to validate tokens without needing the private key.

This enables scenarios where:
- Multiple microservices validate the same JWT
- Third-party services can verify your tokens

---

### Keycloak Integration

Bit Boilerplate includes built-in support for **Keycloak**, a free, open-source identity and access management solution. Keycloak provides enterprise-grade features like:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,6 @@ In [`src/Server/Boilerplate.Server.Api/appsettings.json`](/src/Server/Boilerplat
}
},
"Identity": {
"JwtIssuerSigningKeySecret": "VeryLongJWTIssuerSigningKeySecret...",
"Issuer": "Boilerplate",
"Audience": "Boilerplate",
"BearerTokenExpiration": "0.00:05:00",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIDEzCCAfugAwIBAgIUXViovPz6nf8uYwwuLV5wOLvbcGIwDQYJKoZIhvcNAQEL
BQAwGTEXMBUGA1UEAwwOQXBwQ2VydGlmaWNhdGUwHhcNMjYwMjIzMTYzODE1WhcN
MjcwMjIzMTYzODE1WjAZMRcwFQYDVQQDDA5BcHBDZXJ0aWZpY2F0ZTCCASIwDQYJ
KoZIhvcNAQEBBQADggEPADCCAQoCggEBANdMHBLKxFtpHcWN/UKYy0larN0xgXy+
ZhTPFLZ+3p4eHNZ8kxI2VkNk/6DZBkTlLDPTacURa9BLnfkkg8xamYG7IfUZZLM4
MXu5pN2C3f3FnhgjT0IU0x2S31FrkSClqgJ9zbUIkJgeyRiHkidCBS6fr2FF152h
9LPRDo5jlCAbDWK1jQnp0ccMWfenBqWbE9UiHMjFSNEsGsuLn9VA8MbcPOSUe3D4
4i5ykQS7l9Nu/1IgSgCAR1JWtApE/KS5KGmm7zdZDywKIhgl2q4BBTklTKLsP36z
kKqvvRXwQpYgO3MyPmQ1D46qkt3xjJX50mGGmanj7f7EL3yWrJVOPdsCAwEAAaNT
MFEwHQYDVR0OBBYEFHBg04f5muvXzVwIN8MMNg1/DWJMMB8GA1UdIwQYMBaAFHBg
04f5muvXzVwIN8MMNg1/DWJMMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL
BQADggEBAEjb64p3HnbxALYXFhxv82hAcQcAzGeXnBTpDbNOgTa4zt3H7YJLbgOp
SDqcoQISFjnF7NByYPtbXWX7EyG6yGygB/BbC0H4TI0n2v4MCC/qbAayjBdtByIg
zgc8UrVIWripOMUcvadS58zpyNo2+2UcAxZpE+AJwUCJUdhFdz+aDRTvvQEOVGhJ
rGf3GptXgClrO82LlkOydnXs0JeHibdH97aNt84/LZJN/Su/GqJO7UKf2cQeib5K
W/HKnyGgKbOQmwyWPGQLh9tweVx1Ckd3NwXaeW8+9vHfzPGGKodWjFmpYA4AdWQZ
DoxFeE5vdH2fydJFZCH5vNU8YxXAxBc=
-----END CERTIFICATE-----
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDXTBwSysRbaR3F
jf1CmMtJWqzdMYF8vmYUzxS2ft6eHhzWfJMSNlZDZP+g2QZE5Swz02nFEWvQS535
JIPMWpmBuyH1GWSzODF7uaTdgt39xZ4YI09CFNMdkt9Ra5EgpaoCfc21CJCYHskY
h5InQgUun69hRdedofSz0Q6OY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e1J42SEAnpTgO6ylCkLGb+Nl2vAz/4OL6On2r6wjFE10u860gFGSTrN6lQEAUE8z
dzY7rNJqD17sThvBW48BbsGNsGtSMhlKH/xsTy46fPvEMNewfoJKlNMh7YDyOLwk
GMLjEkY04GdqbsbcKV1/DmxOlw14TR63ykpgtNShAoGAdFJVLKPPrYDvqOmS3NvX
yhdFc9bmyUsEMqmEe3jAI9tKgP/7SG3VWTR6dpwWTqVymAs/MC/kxJbD+FY5rxXM
bwxv0ySXlMBu63abQs9sUAJ735KPq/ZPjOG2Wis68xjcRR39M++sTjRZOS23lvm/
tlSi3Jk82ZghOYaW/YquRnE=
-----END PRIVATE KEY-----
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# Application Certificate Management

This document explains how the application uses cryptographic certificates for security, including JWT authentication and Data Protection.

## Overview

The application uses asymmetric cryptography (public/private key pairs) for two critical security functions:

1. **JWT Token Signing & Validation** - Securely issue and verify access tokens
2. **Data Protection API** - Encrypt sensitive data at rest

## Benefits of Public/Private Key Pairs

### JWT Token Signing

| Key Type | Purpose |
|----------|---------|
| **Private Key** | Used by the **issuing server** to **sign** JWT tokens. This key must be kept secret and secure. |
| **Public Key** | Used by **any service** to **validate** JWT tokens. This key can be freely distributed. |

**Advantages:**
- Other backend services can validate tokens without needing the private key
- Compromising the public key doesn't allow token forgery
- Follows the principle of least privilege

### Data Protection API

| Key Type | Purpose |
|----------|---------|
| **Private Key** | Used to **decrypt** protected data (cookies, anti-forgery tokens, etc.) |
| **Public Key** | Used to **encrypt** data for protection |

**Advantages:**
- Consistent encryption across multiple server instances
- Survives application restarts without invalidating protected data
- Enables load-balanced deployments with shared encryption keys

## Generating Certificates

Use OpenSSL to generate the required certificate files:

```shell
# 1. Generate the private key (2048-bit RSA)
openssl genrsa -out AppCertificate.key 2048

# 2. Generate a self-signed X.509 certificate (valid for 1 year)
openssl req -new -x509 -key AppCertificate.key -out AppCertificate.crt -days 365 -subj "/CN=AppCertificate"
```

## OpenID Configuration Endpoint

The application exposes an OpenID Connect discovery endpoint at `/.well-known/openid-configuration`. This endpoint provides:

- **JWKS (JSON Web Key Set)** - Contains the public key for token validation
- **Issuer information** - Identifies the token issuer
- **Supported algorithms** - Lists the signing algorithms used

### Why Expose This Endpoint?

This allows **other backend services** to securely validate JWTs issued by this API without:
- Sharing the private key
- Hardcoding the public key
- Manual key distribution

The public key is automatically fetched and cached by consuming services.

## Integrating Other Backend Services

Other .NET services can validate tokens issued by this API using the following configuration:

```cs
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "http://localhost:5030";
options.RequireHttpsMetadata = builder.Environment.IsDevelopment() is false;
options.TokenValidationParameters = new()
{
ClockSkew = TimeSpan.Zero,
RequireSignedTokens = true,

ValidateIssuerSigningKey = true,

RequireExpirationTime = true,

ValidateAudience = true,
ValidAudience = "Boilerplate",

ValidateIssuer = true,
ValidIssuer = "Boilerplate"
};

// OR

options.TokenValidationParameters = new()
{
ValidateAudience = false,

ValidateIssuer = true,
ValidIssuer = "Boilerplate"
};
});

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();
```

### How It Works

1. The consuming service calls `/.well-known/openid-configuration` on startup
2. It retrieves the JWKS endpoint URL from the configuration
3. It fetches the public key(s) from the JWKS endpoint
4. Incoming JWTs are validated using the fetched public key
5. Keys are cached and periodically refreshed

This pattern enables a **zero-trust architecture** where services can independently verify token authenticity without sharing secrets.
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@
<StronglyTypedClassName>EmailStrings</StronglyTypedClassName>
<PublicClass>true</PublicClass>
</EmbeddedResource>

<None Update="AppCertificate.*">
<DependentUpon>AppCertificate.md</DependentUpon>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

<!--
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Authentication;
using Boilerplate.Server.Api.Infrastructure.Services;

namespace Boilerplate.Server.Api.Features.Identity.Services;

Expand All @@ -12,6 +12,7 @@ public partial class AppJwtSecureDataFormat
: ISecureDataFormat<AuthenticationTicket>
{
private readonly string tokenType;
private readonly RsaSecurityKey privateKey;
private readonly ServerApiSettings appSettings;
private readonly ILogger<AppJwtSecureDataFormat> logger;
private readonly TokenValidationParameters validationParameters;
Expand All @@ -25,13 +26,16 @@ public AppJwtSecureDataFormat(ServerApiSettings appSettings,
this.tokenType = tokenType;
this.appSettings = appSettings;

privateKey = AppCertificateService.GetPrivateSecurityKey();

validationParameters = new()
{
ClockSkew = TimeSpan.Zero,
RequireSignedTokens = true,

IssuerSigningKey = AppCertificateService.GetPublicSecurityKey(),
ValidAlgorithms = [SecurityAlgorithms.RsaSha256],
ValidateIssuerSigningKey = env.IsDevelopment() is false,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.Identity.JwtIssuerSigningKeySecret)),

RequireExpirationTime = true,
ValidateLifetime = tokenType is "AccessToken", /* IdentityController.Refresh will validate expiry itself while refreshing the token */
Expand Down Expand Up @@ -105,7 +109,7 @@ public string Protect(AuthenticationTicket data, string? purpose)
Audience = appSettings.Identity.Audience,
IssuedAt = DateTimeOffset.UtcNow.DateTime,
Expires = data.Properties.ExpiresUtc!.Value.UtcDateTime,
SigningCredentials = new SigningCredentials(validationParameters.IssuerSigningKey, SecurityAlgorithms.HmacSha512),
SigningCredentials = new SigningCredentials(privateKey, SecurityAlgorithms.RsaSha256Signature),
Subject = new ClaimsIdentity(data.Principal.Claims),
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,28 +24,5 @@ public static bool ContainsExpiredAccessToken(this HttpContext context)
{
return context.User.IsAuthenticated() is false && context.Request.Headers.Authorization.Any() is true;
}

public static string? GetAccessToken(this HttpContext context)
{
// 1. Priority: Header (Explicit & CSRF-safe)
// We check the Authorization header first. If a client (e.g., Blazor Hybrid App)
// explicitly sends a token, it takes precedence over any potentially stale or unrelated cookies.
// This aligns with the 'AutoCsrfProtectionFilter' logic, which treats header-based requests as secure.
string? authHeader = context.Request.Headers.Authorization;
if (string.IsNullOrEmpty(authHeader) is false && authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
return authHeader["Bearer ".Length..].Trim();
}

// 2. Priority: Cookie (Implicit & requires CSRF checks)
// If no header is found, we fall back to the cookie.
// This is typically used for standard web browser clients.
if (context.Request.Cookies.TryGetValue("access_token", out var cookieToken))
{
return cookieToken;
}

return null;
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography.X509Certificates;

namespace Boilerplate.Server.Api.Infrastructure.Services;

/// <summary>
/// For more information, checkout AppCertificate.md file in the root directory of the server project.
/// </summary>
public static class AppCertificateService
{
private static X509Certificate2? appCert;
private static RsaSecurityKey? privateSecurityKey;
private static RsaSecurityKey? publicSecurityKey;

/// <summary>
/// This would return AppCertificate containing private key and public key.
/// </summary>
public static X509Certificate2 GetAppCertificate()
{
if (appCert is not null)
return appCert;

var keyPemFilePath = Path.Combine(AppContext.BaseDirectory, "AppCertificate.key");
var certPemFilePath = Path.Combine(AppContext.BaseDirectory, "AppCertificate.crt");

appCert = X509Certificate2.CreateFromPemFile(certPemFilePath, keyPemFilePath); // This would work even in restricted shared hosting environments where you don't have access to certificate store.
// You could also use pfx file with password or using vaults such as Azure Key Vault etc.

if (AppEnvironment.IsDevelopment() is false && appCert.Thumbprint is "435DA2895E4409117594DD923571666FA01352B1")
throw new InvalidOperationException("You are using the default self-signed certificate in non-development environment. Please use a secure certificate in production.");

return appCert;
}

/// <summary>
/// This would return the private key of app certificate to issue JWT tokens.
/// </summary>
public static RsaSecurityKey GetPrivateSecurityKey()
{
return privateSecurityKey ??= new RsaSecurityKey(GetAppCertificate().GetRSAPrivateKey() ?? throw new InvalidOperationException("Private key not found in the certificate.")) { KeyId = "Boilerplate" };
}

/// <summary>
/// This would return the public key of app certificate to validate JWT tokens.
/// </summary>
public static RsaSecurityKey GetPublicSecurityKey()
{
return publicSecurityKey ??= new RsaSecurityKey(GetAppCertificate().GetRSAPublicKey() ?? throw new InvalidOperationException("Public key not found in the certificate.")) { KeyId = "Boilerplate" };
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ public async Task<DiagnosticLogDto[]> GetUserSessionLogs(Guid userSessionId, [Fr

private async Task ChangeAuthenticationStateImplementation(ClaimsPrincipal? user)
{
if (Context.ConnectionAborted.IsCancellationRequested)
return;

Context.GetHttpContext()!.User = user ?? new ClaimsPrincipal(new ClaimsIdentity()) /*Anonymous*/;

await using var scope = serviceProvider.CreateAsyncScope();
Expand Down
Loading
Loading