-
-
Notifications
You must be signed in to change notification settings - Fork 268
Use public/private key in bit Boilerplate for data protection and jwt issue/validation (#12120) #12121
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Use public/private key in bit Boilerplate for data protection and jwt issue/validation (#12120) #12121
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
1217efd
use public/private key in bit Boilerplate for data protection and jwt…
yasmoradi 6773038
fix
yasmoradi 8687f62
fix
yasmoradi a7fe74b
fix
yasmoradi 65ded9c
fix
yasmoradi 416df2f
fix
yasmoradi ffc29fe
Update src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerpla…
yasmoradi 464d70b
fix
yasmoradi a8e3ec9
fix
yasmoradi c145678
fix
yasmoradi 2eda495
fix
yasmoradi af87dfa
fix
yasmoradi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
19 changes: 19 additions & 0 deletions
19
...emplates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/AppCertificate.crt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| -----BEGIN CERTIFICATE----- | ||
| MIIDEzCCAfugAwIBAgIUXViovPz6nf8uYwwuLV5wOLvbcGIwDQYJKoZIhvcNAQEL | ||
| BQAwGTEXMBU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-----END CERTIFICATE----- |
28 changes: 28 additions & 0 deletions
28
...emplates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/AppCertificate.key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| -----BEGIN PRIVATE KEY----- | ||
| MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDXTBwSysRbaR3F | ||
| jf1CmMtJWqzdMYF8vmYUzxS2ft6eHhzWfJMSNlZDZP+g2QZE5Swz02nFEWvQS535 | ||
| JIPMWpmBuyH1GWSzODF7uaTdgt39xZ4YI09CFNMdkt9Ra5EgpaoCfc21CJCYHskY | ||
| h5InQgUun69hRdedofSz0Q6OY5QgGw1itY0J6dHHDFn3pwalmxPVIhzIxUjRLBrL | ||
| i5/VQPDG3DzklHtw+OIucpEEu5fTbv9SIEoAgEdSVrQKRPykuShppu83WQ8sCiIY | ||
| JdquAQU5JUyi7D9+s5Cqr70V8EKWIDtzMj5kNQ+OqpLd8YyV+dJhhpmp4+3+xC98 | ||
| lqyVTj3bAgMBAAECggEAAMpgWkCsB0N/YrpQ0ngE1m4yARjMKJm9kwQQ65Biu8FB | ||
| 1Lr8h5SXBC10XG+ixFZQhm+NF7ZkLvQYIGaMKdKmOIbtIzvQy81uI6Th5rsehjFN | ||
| Kvy4w4p4/ok0e+n4jxbE9I9OftutCGcUiSZcr9J0ow46une/gQLAMBHMw5AfKTI2 | ||
| MAqcW7z7qd2asiuGcgnXvMxvXM6qufEAUpg6O/cpHlMefoyVWKfBh3tiao6BTho3 | ||
| vIFgIT5BiMzmDRwCIjdRUNIKG5cQAUC9V0sXxj9N9rlNtmgautxsNE05oi5tGYZ6 | ||
| ytzySNyvPicRa4Mfg6rSZxj80zDNHI32SeTmViQQAQKBgQDz9CRqBnIXaApdPWT5 | ||
| IxoURDcWP4A0Bdaa7AdL6qdQNuNbQja7f9jCeduZndxvd41bZmF79X/X2LhNReY8 | ||
| u2HQUy3dpbh3sVbflHxIrlPXMejcX/eUaQJoK30T+gyLu3uo/99Jlj3+5Jt+KVsv | ||
| LVnwnFAW5Bg1wZTTrTn0rlSfSwKBgQDh7bewr1E3K53Qtlz48+ZCCGTljhbwZwct | ||
| EaezinpYrzV090MjOEsTlHgCyJ1usPwcFno21OObtoUR6E6Im+HifnphBtm0FHYe | ||
| DcEHuNOX9Jx8JPAODsODpCUyl2aFi0KzvtX9mqLeU6+JHAJ23aDp8OzkHW1w1tnz | ||
| c8zQPfRxsQKBgEiqIyKVsuw36EZnoCj5hK4et43f8k8MoiTZQz8gsR+aidRH/8eP | ||
| yD/9TiUOuXdWU/uynjzvHlprylHyDSdv5S3JaPMJhs3YO/ky4GZBzuVdj2/9AeDp | ||
| +naO5Z3KsGv6t1XaiWcA4oyHCa3loayGxLB/zvdSj8eLVspKYeX4+2nLAoGBAN0Q | ||
| e1J42SEAnpTgO6ylCkLGb+Nl2vAz/4OL6On2r6wjFE10u860gFGSTrN6lQEAUE8z | ||
| dzY7rNJqD17sThvBW48BbsGNsGtSMhlKH/xsTy46fPvEMNewfoJKlNMh7YDyOLwk | ||
| GMLjEkY04GdqbsbcKV1/DmxOlw14TR63ykpgtNShAoGAdFJVLKPPrYDvqOmS3NvX | ||
| yhdFc9bmyUsEMqmEe3jAI9tKgP/7SG3VWTR6dpwWTqVymAs/MC/kxJbD+FY5rxXM | ||
| bwxv0ySXlMBu63abQs9sUAJ735KPq/ZPjOG2Wis68xjcRR39M++sTjRZOS23lvm/ | ||
| tlSi3Jk82ZghOYaW/YquRnE= | ||
| -----END PRIVATE KEY----- |
118 changes: 118 additions & 0 deletions
118
...Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/AppCertificate.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
|
|
||
yasmoradi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ### 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. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
50 changes: 50 additions & 0 deletions
50
...rplate/src/Server/Boilerplate.Server.Api/Infrastructure/Services/AppCertificateService.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"); | ||
|
|
||
yasmoradi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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" }; | ||
| } | ||
yasmoradi marked this conversation as resolved.
Show resolved
Hide resolved
yasmoradi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.