From 8c4cfa141fe7b7763b218ff7887e310a2e2fd008 Mon Sep 17 00:00:00 2001 From: Giuseppe Graziano Date: Tue, 24 Feb 2026 13:24:35 +0100 Subject: [PATCH] [OID4VCI] Improve signing key selection Closes #45385 Signed-off-by: Giuseppe Graziano --- .../admin/messages/messages_en.properties | 5 +- .../src/client-scopes/details/ScopeForm.tsx | 63 ++++++++++----- .../details/oid4vciAttributes.ts | 1 - .../client-scope/oid4vci-client-scope.spec.ts | 4 +- .../oid4vc/model/CredentialBuildConfig.java | 17 +++- .../oid4vc/OID4VCJWTIssuerEndpointTest.java | 77 +++++++++++++++++++ 6 files changed, 141 insertions(+), 26 deletions(-) diff --git a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties index a682c0dbd74..bff13bd1c91 100644 --- a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties +++ b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties @@ -3689,7 +3689,7 @@ supportedFormatsHelp=The format of the verifiable credential. Currently supporte credentialDisplay=Credential Display credentialDisplayHelp=JSON array of objects containing display metadata for wallets (name, logo, colors, etc.). Example: [{"name": "IdentityCredential", "locale": "en-US", "logo": {"uri": "https://example.com/logo.png", "alt_text": "Logo"}, "background_color": "#12107c", "text_color": "#FFFFFF"}] credentialSigningAlgorithm=Credential Signing Algorithm -credentialSigningAlgorithmHelp=Signing algorithm used to sign credentials (for example "ES256"). Leave blank to use the realm defaults derived from available keys. +credentialSigningAlgorithmHelp=Signing algorithm used to select the active realm key for signing credentials (e.g., "ES256"). If not specified, the active key will be selected using the realm's default algorithm. This option is disabled if a specific 'Signing Key ID' is selected. hashAlgorithm=Hash Algorithm hashAlgorithmHelp=Hash algorithm used for SD-JWT credentials (for example "SHA-256"). Defaults to "SHA-256" if not specified. supportedCredentialTypes=Supported Credential Types @@ -3701,8 +3701,9 @@ tokenJwsTypeHelp=The type value written into the typ header of the JWT. Defaults visibleClaims=Visible Claims visibleClaimsHelp=Comma-separated list of claims that are always disclosed in the SD-JWT body (e.g., "id,iat,nbf,exp,jti,given_name"). Defaults to "id,iat,nbf,exp,jti". Only applicable for SD-JWT format. signingKeyId=Signing Key ID -signingKeyIdHelp=Optional. The ID of the realm key used to sign the credential. If not specified, the realm's active signing key of the algorithm specified by 'Credential Signing Algorithm' (if set) will be used automatically. If this option is specified, it is highly recommended to specify also 'Credential Signing Algorithm' as the Signing Key ID must be of the algorithm specified by that option. +signingKeyIdHelp=Optional. The ID of the realm key used to sign the credential. If not specified, the realm's active signing key of the algorithm specified by 'Credential Signing Algorithm' (if set) will be used automatically. If a specific key is selected here, the 'Credential Signing Algorithm' option will be disabled and automatically set to the key's algorithm. useDefaultKey=Use default (realm's active signing key) +useDefaultAlg=Use default algorithm # Workflows workflows=Workflows titleWorkflows=Workflows diff --git a/js/apps/admin-ui/src/client-scopes/details/ScopeForm.tsx b/js/apps/admin-ui/src/client-scopes/details/ScopeForm.tsx index 90304a805b0..93896b57123 100644 --- a/js/apps/admin-ui/src/client-scopes/details/ScopeForm.tsx +++ b/js/apps/admin-ui/src/client-scopes/details/ScopeForm.tsx @@ -17,8 +17,8 @@ import { useAdminClient } from "../../admin-client"; import { getProtocolName } from "../../clients/utils"; import { DefaultSwitchControl } from "../../components/SwitchControl"; import { - ClientScopeDefaultOptionalType, allClientScopeTypes, + ClientScopeDefaultOptionalType, } from "../../components/client-scope/ClientScopeTypes"; import { FormAccess } from "../../components/form/FormAccess"; import { useRealm } from "../../context/realm-context/RealmContext"; @@ -69,15 +69,6 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => { const isFeatureEnabled = useIsFeatureEnabled(); const isDynamicScopesEnabled = isFeatureEnabled(Feature.DynamicScopes); - // Get available signature algorithms from server info - const signatureAlgorithms = useMemo( - () => - serverInfo?.providers?.signature?.providers - ? Object.keys(serverInfo.providers.signature.providers) - : [], - [serverInfo], - ); - // Get available hash algorithms from server info const hashAlgorithms = serverInfo?.providers?.hash?.providers ? Object.keys(serverInfo.providers.hash.providers).map((alg) => @@ -86,11 +77,20 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => { : []; // Get available asymmetric signature algorithms from server info - const asymmetricSigAlgOptions = useMemo( + const asymmetricAlgorithms = useMemo( () => serverInfo?.cryptoInfo?.clientSignatureAsymmetricAlgorithms ?? [], [serverInfo], ); + const asymmetricSigAlgOptions = useMemo(() => { + const mappedOptions = asymmetricAlgorithms.map((alg) => ({ + key: alg, + value: alg, + })); + + return [{ key: "", value: t("useDefaultAlg") }, ...mappedOptions]; + }, [asymmetricAlgorithms, t]); + // Fetch realm keys for signing_key_id dropdown const [realmKeys, setRealmKeys] = useState([]); @@ -104,7 +104,7 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => { ); // Prepare key options for SelectControl - // Filter only active keys suitable for signing credentials + // Filter only active keys suitable for signing credentials AND using asymmetric algorithms const keyOptions = useMemo(() => { const options = [{ key: "", value: t("useDefaultKey") }]; if (realmKeys && realmKeys.length > 0) { @@ -114,7 +114,7 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => { key.kid && key.status === "ACTIVE" && key.algorithm && - signatureAlgorithms.includes(key.algorithm), + asymmetricAlgorithms.includes(key.algorithm), ) .map((key) => ({ key: key.kid!, @@ -123,7 +123,7 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => { options.push(...keyOptions); } return options; - }, [realmKeys, signatureAlgorithms, t]); + }, [realmKeys, asymmetricAlgorithms, t]); const displayOnConsentScreen: string = useWatch({ control, @@ -159,6 +159,14 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => { realmRepresentation?.verifiableCredentialsEnabled; const isNotSaml = selectedProtocol != "saml"; + const isSigningKeySelected = useWatch({ + control, + name: convertAttributeNameToForm( + "attributes.vc.signing_key_id", + ), + defaultValue: clientScope?.attributes?.["vc.signing_key_id"] ?? "", + }); + const setDynamicRegex = (value: string, append: boolean) => setValue( convertAttributeNameToForm( @@ -172,9 +180,26 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => { convertToFormValues(clientScope ?? {}, setValue); }, [clientScope, setValue]); + useEffect(() => { + if (isSigningKeySelected) { + const selectedKeyInfo = realmKeys.find( + (k) => k.kid === isSigningKeySelected, + ); + if (selectedKeyInfo?.algorithm) { + setValue( + convertAttributeNameToForm( + "attributes.vc.credential_signing_alg", + ), + selectedKeyInfo.algorithm, + { shouldDirty: true }, + ); + } + } + }, [isSigningKeySelected, realmKeys, setValue]); + /* Form-level validation handles correctness; here we only prune known optional - OID4VC fields when empty. If new attributes are added, extend - OID4VC_ATTRIBUTE_KEYS (and related validation) so they participate in cleanup. */ + OID4VC fields when empty. If new attributes are added, extend + OID4VC_ATTRIBUTE_KEYS (and related validation) so they participate in cleanup. */ const onSubmit = (values: ClientScopeDefaultOptionalType) => { const isOid4vc = values.protocol === OID4VC_PROTOCOL; const cleaned = isOid4vc ? removeEmptyOid4vcAttributes(values) : values; @@ -408,10 +433,8 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => { clientScope?.attributes?.["vc.credential_signing_alg"] ?? "", }} - options={asymmetricSigAlgOptions.map((alg) => ({ - key: alg, - value: alg, - }))} + options={asymmetricSigAlgOptions} + isDisabled={!!isSigningKeySelected} /> )} {hashAlgorithms.length > 0 && ( diff --git a/js/apps/admin-ui/src/client-scopes/details/oid4vciAttributes.ts b/js/apps/admin-ui/src/client-scopes/details/oid4vciAttributes.ts index d131dd18f49..0f13f052080 100644 --- a/js/apps/admin-ui/src/client-scopes/details/oid4vciAttributes.ts +++ b/js/apps/admin-ui/src/client-scopes/details/oid4vciAttributes.ts @@ -11,7 +11,6 @@ export const OID4VC_ATTRIBUTE_KEYS = [ "vc.expiry_in_seconds", "vc.credential_build_config.token_jws_type", "vc.supported_credential_types", - "vc.credential_signing_alg", "vc.verifiable_credential_type", "vc.credential_build_config.sd_jwt.visible_claims", "vc.display", diff --git a/js/apps/admin-ui/test/client-scope/oid4vci-client-scope.spec.ts b/js/apps/admin-ui/test/client-scope/oid4vci-client-scope.spec.ts index 6b1af4d3cc4..eb81aa8f546 100644 --- a/js/apps/admin-ui/test/client-scope/oid4vci-client-scope.spec.ts +++ b/js/apps/admin-ui/test/client-scope/oid4vci-client-scope.spec.ts @@ -463,7 +463,9 @@ test.describe("OID4VCI Client Scope Functionality", () => { await navigateBackAndVerifyClientScope(page, testBed, testClientScopeName); await expect(page.getByTestId(OID4VCI_FIELDS.ISSUER_DID)).toHaveValue(""); - await expect(page.locator(OID4VCI_FIELDS.SIGNING_ALGORITHM)).toHaveText(""); + await expect(page.locator(OID4VCI_FIELDS.SIGNING_ALGORITHM)).toContainText( + "Use default algorithm", + ); await expect(page.locator(OID4VCI_FIELDS.HASH_ALGORITHM)).toContainText( "sha-256", ); diff --git a/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialBuildConfig.java b/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialBuildConfig.java index 1d3d76567b8..06ba5101b26 100644 --- a/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialBuildConfig.java +++ b/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialBuildConfig.java @@ -21,6 +21,8 @@ import java.util.Objects; import java.util.Optional; +import org.keycloak.crypto.KeyWrapper; +import org.keycloak.models.Constants; import org.keycloak.models.KeycloakSession; import org.keycloak.models.oid4vci.CredentialScopeModel; import org.keycloak.protocol.oid4vc.issuance.OID4VCIssuerWellKnownProvider; @@ -92,8 +94,19 @@ public static CredentialBuildConfig parse(KeycloakSession keycloakSession, final String credentialIssuer = Optional.ofNullable(credentialModel.getIssuerDid()).orElse( OID4VCIssuerWellKnownProvider.getIssuer(keycloakSession.getContext())); - String modelSigningAlg = credentialModel.getSigningAlg(); - String signingAlg = StringUtil.isNotBlank(modelSigningAlg) ? modelSigningAlg : credentialConfiguration.getCredentialSigningAlgValuesSupported().get(0); + + String signingAlg = Constants.DEFAULT_SIGNATURE_ALGORITHM; + if (StringUtil.isNotBlank(credentialModel.getSigningKeyId())) { + signingAlg = keycloakSession.keys() + .getKeysStream(keycloakSession.getContext().getRealm()) + .filter(key-> key.getKid().equals(credentialModel.getSigningKeyId())) + .findAny() + .map(KeyWrapper::getAlgorithm) + .orElse(Constants.DEFAULT_SIGNATURE_ALGORITHM); + } + else if (StringUtil.isNotBlank(credentialModel.getSigningAlg())) { + signingAlg = credentialModel.getSigningAlg(); + } return new CredentialBuildConfig().setCredentialIssuer(credentialIssuer) .setCredentialConfigId(credentialConfiguration.getId()) diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCJWTIssuerEndpointTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCJWTIssuerEndpointTest.java index 6595b6b157c..7c71d06b5d3 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCJWTIssuerEndpointTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCJWTIssuerEndpointTest.java @@ -45,12 +45,15 @@ import org.keycloak.common.util.BouncyIntegration; import org.keycloak.common.util.KeyUtils; import org.keycloak.common.util.Time; +import org.keycloak.crypto.Algorithm; import org.keycloak.crypto.ECDSASignatureSignerContext; import org.keycloak.crypto.KeyUse; import org.keycloak.crypto.KeyWrapper; import org.keycloak.jose.jwk.JWK; import org.keycloak.jose.jwk.JWKBuilder; import org.keycloak.jose.jws.JWSBuilder; +import org.keycloak.jose.jws.JWSHeader; +import org.keycloak.models.Constants; import org.keycloak.models.RealmModel; import org.keycloak.models.oid4vci.CredentialScopeModel; import org.keycloak.protocol.oid4vc.OID4VCLoginProtocolFactory; @@ -81,6 +84,7 @@ import org.keycloak.representations.JsonWebToken; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.ClientScopeRepresentation; +import org.keycloak.representations.idm.KeysMetadataRepresentation; import org.keycloak.representations.idm.OAuth2ErrorRepresentation; import org.keycloak.services.CorsErrorResponseException; import org.keycloak.services.managers.AppAuthManager.BearerTokenAuthenticator; @@ -1316,6 +1320,79 @@ public void testCredentialOfferDifferentNoncesIndependent() { assertEquals(ErrorType.INVALID_CREDENTIAL_OFFER_REQUEST.getValue(), response2.getError(), "Error type should be INVALID_CREDENTIAL_OFFER_REQUEST"); } + @Test + public void testCredentialIssuerSigningDefaultKeyAndAlg() { + KeysMetadataRepresentation keyMetadata = testRealm.admin().keys().getKeyMetadata(); + + String kid = ""; + String alg = ""; + jwtTypeCredentialScope.getAttributes().put(CredentialScopeModel.VC_SIGNING_KEY_ID, kid); + jwtTypeCredentialScope.getAttributes().put(CredentialScopeModel.VC_SIGNING_ALG, alg); + testRealm.admin().clientScopes().get(jwtTypeCredentialScope.getId()).update(jwtTypeCredentialScope); + testCredentialIssuanceSigningConfiguration(keyMetadata.getActive().get(Constants.DEFAULT_SIGNATURE_ALGORITHM), Constants.DEFAULT_SIGNATURE_ALGORITHM); + } + + @Test + public void testCredentialIssuerSigningSpecificAlg() { + String kid = ""; + String alg = Algorithm.ES256; + jwtTypeCredentialScope.getAttributes().put(CredentialScopeModel.VC_SIGNING_KEY_ID, kid); + jwtTypeCredentialScope.getAttributes().put(CredentialScopeModel.VC_SIGNING_ALG, alg); + testRealm.admin().clientScopes().get(jwtTypeCredentialScope.getId()).update(jwtTypeCredentialScope); + testCredentialIssuanceSigningConfiguration(null, Algorithm.ES256); + } + + @Test + public void testCredentialIssuerSigningSpecificKey() { + KeysMetadataRepresentation keyMetadata = testRealm.admin().keys().getKeyMetadata(); + + String kid = keyMetadata.getActive().get(Constants.DEFAULT_SIGNATURE_ALGORITHM); + String alg = Constants.DEFAULT_SIGNATURE_ALGORITHM; + jwtTypeCredentialScope.getAttributes().put(CredentialScopeModel.VC_SIGNING_KEY_ID, kid); + jwtTypeCredentialScope.getAttributes().put(CredentialScopeModel.VC_SIGNING_ALG, alg); + testRealm.admin().clientScopes().get(jwtTypeCredentialScope.getId()).update(jwtTypeCredentialScope); + testCredentialIssuanceSigningConfiguration(keyMetadata.getActive().get(Constants.DEFAULT_SIGNATURE_ALGORITHM), Constants.DEFAULT_SIGNATURE_ALGORITHM); + } + + public void testCredentialIssuanceSigningConfiguration(String kid, String alg) { + String scopeName = jwtTypeCredentialScope.getName(); + String credConfigId = jwtTypeCredentialScope.getAttributes().get(CredentialScopeModel.VC_CONFIGURATION_ID); + CredentialIssuer credentialIssuer = getCredentialIssuerMetadata(); + OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail(); + authDetail.setType(OPENID_CREDENTIAL); + authDetail.setCredentialConfigurationId(credConfigId); + authDetail.setLocations(List.of(credentialIssuer.getCredentialIssuer())); + + testCredentialIssuanceWithAuthZCodeFlow(jwtTypeCredentialScope, + (testScope) -> { + String authCode = getAuthorizationCode(oauth, client, "john", scopeName); + return getBearerToken(oauth, authCode, authDetail).getAccessToken(); + }, + m -> { + String accessToken = (String) m.get("accessToken"); + WebTarget credentialTarget = (WebTarget) m.get("credentialTarget"); + CredentialRequest credentialRequest = (CredentialRequest) m.get("credentialRequest"); + + try (Response response = credentialTarget.request() + .header(HttpHeaders.AUTHORIZATION, "bearer " + accessToken) + .post(Entity.json(credentialRequest))) { + assertEquals(200, response.getStatus()); + CredentialResponse credentialResponse = JsonSerialization.readValue(response.readEntity(String.class), + CredentialResponse.class); + JWSHeader jwsHeader = TokenVerifier.create((String) credentialResponse.getCredentials().get(0).getCredential(), + JsonWebToken.class).getHeader(); + + if (kid != null) { + assertEquals(jwsHeader.getKeyId(), kid); + } + assertEquals(jwsHeader.getRawAlgorithm(), alg); + + } catch (VerificationException | IOException e) { + throw new RuntimeException(e); + } + }); + } + private String getCNonce() { UriBuilder builder = UriBuilder.fromUri(keycloakUrls.getBase()); URI oid4vcUri = RealmsResource.protocolUrl(builder)