-
Notifications
You must be signed in to change notification settings - Fork 3.7k
feat: add private_key_jwt client authentication support and abp generate-jwks CLI command
#25068
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
Changes from 4 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
38d9073
Add JWKS private key and public key set for OpenIddict integration
maliming dc195e2
chore: upgrade Microsoft.IdentityModel packages from 8.14.0 to 8.16.0
maliming 2c5b124
docs: update package version changes [skip ci]
github-actions[bot] a682d81
fix: address Copilot review issues in OpenIddict JWKS demo app and CL…
maliming 3786ddf
fix: copy jwks.json to client output and use ILogger in ServerDataSee…
maliming 4d86584
Add OpenIddict private_key_jwt JWKS article
maliming 356d1eb
Optimised images with calibre/image-actions
github-actions[bot] 13261c1
Update article title to private_key_jwt (ABP 10.3)
maliming 4f99825
Merge branch 'private_key_jwt' of github.com:abpframework/abp into pr…
maliming 4662bc7
Optimised images with calibre/image-actions
github-actions[bot] fbd91da
docs: add community article for private_key_jwt client authentication…
maliming dd77065
Optimised images with calibre/image-actions
github-actions[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
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
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
173 changes: 173 additions & 0 deletions
173
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/GenerateJwksCommand.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,173 @@ | ||
| using System; | ||
| using System.IO; | ||
| using System.Security.Cryptography; | ||
| using System.Text; | ||
| using System.Text.Json; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.Extensions.Logging.Abstractions; | ||
| using Volo.Abp.Cli.Args; | ||
| using Volo.Abp.DependencyInjection; | ||
|
|
||
| namespace Volo.Abp.Cli.Commands; | ||
|
|
||
| public class GenerateJwksCommand : IConsoleCommand, ITransientDependency | ||
| { | ||
| public const string Name = "generate-jwks"; | ||
|
|
||
| public ILogger<GenerateJwksCommand> Logger { get; set; } | ||
|
|
||
| public GenerateJwksCommand() | ||
| { | ||
| Logger = NullLogger<GenerateJwksCommand>.Instance; | ||
| } | ||
|
|
||
| public Task ExecuteAsync(CommandLineArgs commandLineArgs) | ||
| { | ||
| var outputDir = commandLineArgs.Options.GetOrNull("output", "o") | ||
| ?? Directory.GetCurrentDirectory(); | ||
| var keySizeStr = commandLineArgs.Options.GetOrNull("key-size", "s") ?? "2048"; | ||
| var alg = commandLineArgs.Options.GetOrNull("alg") ?? "RS256"; | ||
| var kid = commandLineArgs.Options.GetOrNull("kid") ?? Guid.NewGuid().ToString("N"); | ||
| var filePrefix = commandLineArgs.Options.GetOrNull("file", "f") ?? "jwks"; | ||
|
|
||
| if (!int.TryParse(keySizeStr, out var keySize) || (keySize != 2048 && keySize != 4096)) | ||
| { | ||
| Logger.LogError("Invalid key size '{0}'. Supported values: 2048, 4096.", keySizeStr); | ||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| if (!IsValidAlgorithm(alg)) | ||
| { | ||
| Logger.LogError("Invalid algorithm '{0}'. Supported values: RS256, RS384, RS512, PS256, PS384, PS512.", alg); | ||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| if (!Directory.Exists(outputDir)) | ||
| { | ||
| Directory.CreateDirectory(outputDir); | ||
| } | ||
|
|
||
| Logger.LogInformation("Generating RSA {0}-bit key pair (algorithm: {1})...", keySize, alg); | ||
|
|
||
| using var rsa = RSA.Create(); | ||
| rsa.KeySize = keySize; | ||
|
|
||
| var jwksJson = BuildJwksJson(rsa, alg, kid); | ||
| var privateKeyPem = ExportPrivateKeyPem(rsa); | ||
|
|
||
| var jwksFilePath = Path.Combine(outputDir, $"{filePrefix}.json"); | ||
| var privateKeyFilePath = Path.Combine(outputDir, $"{filePrefix}-private.pem"); | ||
|
|
||
| File.WriteAllText(jwksFilePath, jwksJson, Encoding.UTF8); | ||
| File.WriteAllText(privateKeyFilePath, privateKeyPem, Encoding.UTF8); | ||
|
|
||
| Logger.LogInformation(""); | ||
| Logger.LogInformation("Generated files:"); | ||
| Logger.LogInformation(" JWKS (public key) : {0}", jwksFilePath); | ||
| Logger.LogInformation(" Private key (PEM) : {0}", privateKeyFilePath); | ||
| Logger.LogInformation(""); | ||
| Logger.LogInformation("JWKS content (paste this into the ABP OpenIddict application's 'JSON Web Key Set' field):"); | ||
| Logger.LogInformation(""); | ||
| Logger.LogInformation("{0}", jwksJson); | ||
| Logger.LogInformation(""); | ||
| Logger.LogInformation("IMPORTANT: Keep the private key file safe. Never share it or commit it to source control."); | ||
| Logger.LogInformation(" The JWKS file contains only the public key and is safe to share."); | ||
|
|
||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| private static string BuildJwksJson(RSA rsa, string alg, string kid) | ||
| { | ||
| var parameters = rsa.ExportParameters(false); | ||
|
|
||
| var n = Base64UrlEncode(parameters.Modulus); | ||
| var e = Base64UrlEncode(parameters.Exponent); | ||
|
|
||
| using var stream = new System.IO.MemoryStream(); | ||
| using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); | ||
|
|
||
| writer.WriteStartObject(); | ||
| writer.WriteStartArray("keys"); | ||
| writer.WriteStartObject(); | ||
| writer.WriteString("kty", "RSA"); | ||
| writer.WriteString("use", "sig"); | ||
| writer.WriteString("kid", kid); | ||
| writer.WriteString("alg", alg); | ||
| writer.WriteString("n", n); | ||
| writer.WriteString("e", e); | ||
| writer.WriteEndObject(); | ||
| writer.WriteEndArray(); | ||
| writer.WriteEndObject(); | ||
| writer.Flush(); | ||
|
|
||
| return Encoding.UTF8.GetString(stream.ToArray()); | ||
| } | ||
|
maliming marked this conversation as resolved.
|
||
|
|
||
| private static string ExportPrivateKeyPem(RSA rsa) | ||
| { | ||
| #if NET5_0_OR_GREATER | ||
| return rsa.ExportPkcs8PrivateKeyPem(); | ||
| #elif NETSTANDARD2_0 | ||
| // RSA.ExportPkcs8PrivateKey() was introduced in .NET Standard 2.1. | ||
| // The ABP CLI always runs on .NET 5+, so this path is never reached at runtime. | ||
| throw new PlatformNotSupportedException("Private key export requires .NET Standard 2.1 or later."); | ||
| #else | ||
| var privateKeyBytes = rsa.ExportPkcs8PrivateKey(); | ||
| var base64 = Convert.ToBase64String(privateKeyBytes, Base64FormattingOptions.InsertLineBreaks); | ||
| return $"-----BEGIN PRIVATE KEY-----\n{base64}\n-----END PRIVATE KEY-----"; | ||
| #endif | ||
| } | ||
|
|
||
| private static string Base64UrlEncode(byte[] input) | ||
| { | ||
| return Convert.ToBase64String(input) | ||
| .TrimEnd('=') | ||
| .Replace('+', '-') | ||
| .Replace('/', '_'); | ||
| } | ||
|
|
||
| private static bool IsValidAlgorithm(string alg) | ||
| { | ||
| return alg == "RS256" || alg == "RS384" || alg == "RS512" || | ||
| alg == "PS256" || alg == "PS384" || alg == "PS512"; | ||
| } | ||
|
|
||
| public string GetUsageInfo() | ||
| { | ||
| var sb = new StringBuilder(); | ||
|
|
||
| sb.AppendLine(""); | ||
| sb.AppendLine("Usage:"); | ||
| sb.AppendLine(" abp generate-jwks [options]"); | ||
| sb.AppendLine(""); | ||
| sb.AppendLine("Options:"); | ||
| sb.AppendLine(" -o|--output <dir> Output directory (default: current directory)"); | ||
| sb.AppendLine(" -s|--key-size <size> RSA key size: 2048 or 4096 (default: 2048)"); | ||
| sb.AppendLine(" --alg <alg> Algorithm: RS256, RS384, RS512, PS256, PS384, PS512 (default: RS256)"); | ||
| sb.AppendLine(" --kid <id> Key ID (kid) - auto-generated if not specified"); | ||
| sb.AppendLine(" -f|--file <prefix> Output file name prefix (default: jwks)"); | ||
| sb.AppendLine(" Generates: <prefix>.json (JWKS) and <prefix>-private.pem (private key)"); | ||
| sb.AppendLine(""); | ||
| sb.AppendLine("Examples:"); | ||
| sb.AppendLine(" abp generate-jwks"); | ||
| sb.AppendLine(" abp generate-jwks --alg RS512 --key-size 4096"); | ||
| sb.AppendLine(" abp generate-jwks -o ./keys -f myapp"); | ||
| sb.AppendLine(""); | ||
| sb.AppendLine("Description:"); | ||
| sb.AppendLine(" Generates an RSA key pair for use with OpenIddict private_key_jwt client authentication."); | ||
| sb.AppendLine(" The JWKS file (public key) should be pasted into the ABP OpenIddict application's"); | ||
| sb.AppendLine(" 'JSON Web Key Set' field in the management UI."); | ||
| sb.AppendLine(" The private key PEM file should be kept secure and used by the client application"); | ||
| sb.AppendLine(" to sign JWT assertions when authenticating to the token endpoint."); | ||
| sb.AppendLine(""); | ||
| sb.AppendLine("See the documentation for more info: https://abp.io/docs/latest/cli"); | ||
|
|
||
| return sb.ToString(); | ||
| } | ||
|
|
||
| public static string GetShortDescription() | ||
| { | ||
| return "Generates an RSA key pair (JWKS + private key) for OpenIddict private_key_jwt authentication."; | ||
| } | ||
| } | ||
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.