8000 [OID4VCI] Generate pre-authorized codes using the JWT format by IngridPuppet · Pull Request #46450 · keycloak/keycloak · GitHub
[go: up one dir, main page]

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 @@ -22,18 +22,30 @@
* @version $Revision: 1 $
*/
public class VerificationException extends Exception {

private String errorType;

public VerificationException() {
}

public VerificationException(String message) {
super(message);
}

public VerificationException(String message, String errorType) {
super(message);
this.errorType = errorType;
}

public VerificationException(String message, Throwable cause) {
super(message, cause);
}

public VerificationException(Throwable cause) {
super(cause);
}

public String getErrorType() {
return errorType;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -609,7 +609,7 @@ public Response getCredentialOffer(@PathParam("nonce") String nonce) {

// Remove the nonce entry atomically for replay protection
// This prevents the same offer URL from being accessed multiple times
// while keeping pre-authorized code and credential identifier entries available
// while keeping offerId entries available
Map<String, String> removed = session.singleUseObjects().remove(nonce);
if (removed == null) {
var errorMessage = "Credential offer not found or already consumed";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ public interface CredentialOfferStorage extends Provider {

CredentialOfferState getOfferStateByNonce(String nonce);

CredentialOfferState getOfferStateByPreAuthCode(String code);

void removeOfferState(CredentialOfferState entry);

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,19 @@
import java.util.Optional;

import org.keycloak.common.Profile;
import org.keycloak.common.util.SecretGenerator;
import org.keycloak.events.Errors;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.oid4vci.CredentialScopeModel;
import org.keycloak.protocol.oid4vc.issuance.CredentialOfferException;
import org.keycloak.protocol.oid4vc.issuance.OID4VCIssuerWellKnownProvider;
import org.keycloak.protocol.oid4vc.issuance.credentialoffer.preauth.PreAuthCodeHandler;
import org.keycloak.protocol.oid4vc.model.AuthorizationCodeGrant;
import org.keycloak.protocol.oid4vc.model.CredentialsOffer;
import org.keycloak.protocol.oid4vc.model.IssuerState;
import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail;
import org.keycloak.protocol.oid4vc.model.PreAuthCodeCtx;
import org.keycloak.protocol.oid4vc.model.PreAuthorizedCodeGrant;
import org.keycloak.protocol.oid4vc.utils.CredentialScopeModelUtils;
import org.keycloak.util.Strings;
Expand Down Expand Up @@ -106,7 +107,7 @@ public CredentialOfferState createCredentialOffer(
});

if (preAuthorized) {
String code = "urn:oid4vci:code:" + SecretGenerator.getInstance().randomString(64);
String code = createPreAuthorizedCode(offerState);
credOffer.addGrant(new PreAuthorizedCodeGrant().setPreAuthorizedCode(code));
} else {
IssuerState issuerState = new IssuerState().setCredentialsOfferId(offerState.getCredentialsOfferId());
Expand Down Expand Up @@ -146,4 +147,20 @@ private UserModel validateTargetUser(KeycloakSession session, RealmModel realmMo

return targetUserModel;
}

/**
* Creates a pre-authorized code associated with credential offer state.
*/
private String createPreAuthorizedCode(CredentialOfferState offerState) {
PreAuthCodeHandler preAuthCodeHandler = session.getProvider(PreAuthCodeHandler.class);
if (preAuthCodeHandler == null) {
throw new IllegalStateException("No PreAuthCodeHandler provider available");
}

// A PreAuthCodeCtx prevents accidental leaking of sensitive information.
// For instance, transactions codes must never leak into the pre-auth code.
PreAuthCodeCtx ctx = new PreAuthCodeCtx(offerState);

return preAuthCodeHandler.createPreAuthCode(ctx);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,6 @@ public void putOfferState(CredentialOfferState entry) {

// Store with key=nonce
session.singleUseObjects().put(entry.getNonce(), lifespanSeconds, Map.of(ENTRY_KEY, entryJson));

// Store with key=pre_auth_code
entry.getPreAuthorizedCode().ifPresent(preAuthCode ->
session.singleUseObjects().put(preAuthCode, lifespanSeconds, Map.of(ENTRY_KEY, entryJson))
);
}

@Override
Expand All @@ -104,19 +99,10 @@ public CredentialOfferState getOfferStateByNonce(String nonce) {
.orElse(null);
}

10BC8 @Override
public CredentialOfferState getOfferStateByPreAuthCode(String preAuthCode) {
return Optional.ofNullable(session.singleUseObjects().get(preAuthCode))
.map(o -> o.get(ENTRY_KEY))
.map(o -> JsonSerialization.valueFromString(o, CredentialOfferState.class))
.orElse(null);
}

@Override
public void removeOfferState(CredentialOfferState offerState) {
SingleUseObjectProvider singleUseObjects = session.singleUseObjects();
singleUseObjects.remove(offerState.getCredentialsOfferId());
singleUseObjects.remove(offerState.getNonce());
offerState.getPreAuthorizedCode().ifPresent(singleUseObjects::remove);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package org.keycloak.protocol.oid4vc.issuance.credentialoffer.preauth;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import org.keycloak.common.VerificationException;
import org.keycloak.common.util.Base64Url;
import org.keycloak.common.util.SecretGenerator;
import org.keycloak.common.util.Time;
import org.keycloak.events.Errors;
import org.keycloak.models.KeycloakSession;
import org.keycloak.protocol.oid4vc.issuance.OID4VCIssuerWellKnownProvider;
import org.keycloak.protocol.oid4vc.model.JwtPreAuthCode;
import org.keycloak.protocol.oid4vc.model.PreAuthCodeCtx;
import org.keycloak.protocol.oidc.OIDCWellKnownProviderFactory;
import org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation;
import org.keycloak.wellknown.WellKnownProvider;

/**
* Implementation of {@link PreAuthCodeHandler} for JWT pre-authorized codes.
*/
public class JwtPreAuthCodeHandler implements PreAuthCodeHandler {

private final KeycloakSession session;

public JwtPreAuthCodeHandler(KeycloakSession session) {
this.session = session;
}

@Override
public String createPreAuthCode(PreAuthCodeCtx preAuthCodeCtx) {
// Clone and nullify exp claim to avoid duplication
PreAuthCodeCtx clonedCtx = preAuthCodeCtx.clone();
clonedCtx.setExpiresAt(null);

// Building
String salt = Base64Url.encode(SecretGenerator.getInstance().randomBytes());
JwtPreAuthCode jwtBody = (JwtPreAuthCode) new JwtPreAuthCode()
.salt(salt)
.context(clonedCtx)
.issuer(getCredentialIssuer())
.addAudience(getTokenEndpoint())
.issuedNow()
.exp(preAuthCodeCtx.getExpiresAt());

// Signing
return session.tokens().encode(jwtBody);
}

@Override
public PreAuthCodeCtx verifyPreAuthCode(String preAuthCode) throws VerificationException {
// Decode and verify the JWT pre-auth code, and recover jwt payload
JwtPreAuthCode jwtPayload = session.tokens().decode(preAuthCode, JwtPreAuthCode.class);
if (jwtPayload == null) {
throw new VerificationException("Pre-auth code decoding/verification failed");
}

// Perform routine verification on claims
verifyPreAuthCodeClaims(jwtPayload);

// Restore exp information to pre-auth code context
PreAuthCodeCtx preAuthCodeCtx = jwtPayload.getContext();
preAuthCodeCtx.setExpiresAt(jwtPayload.getExp());

return preAuthCodeCtx;
}

/**
* Performs routine verification of the claims in the JWT pre-auth code.
*/
private void verifyPreAuthCodeClaims(JwtPreAuthCode jwtPayload) throws VerificationException {
if (jwtPayload.getContext() == null) {
throw new VerificationException("Not a jwt pre-auth code: no pre-auth code context found");
}

String expectedIssuer = getCredentialIssuer();
if (!expectedIssuer.equals(jwtPayload.getIssuer())) {
String message = String.format(
"Unexpected issuer of jwt pre-auth code: %s (expected) != %s (actual)",
expectedIssuer, jwtPayload.getIssuer());
throw new VerificationException(message);
}

String expectedAudience = getTokenEndpoint();
List<String> actualAudiences = Optional.ofNullable(jwtPayload.getAudience())
.map(Arrays::asList)
.orElse(List.of());

if (actualAudiences.isEmpty() || !actualAudiences.contains(expectedAudience)) {
String message = String.format(
"Invalid audience of jwt pre-auth code: %s (expected) not in %s (actual)",
expectedAudience, actualAudiences);
throw new VerificationException(message);
}

Long exp = jwtPayload.getExp();
if (exp == null) {
throw new VerificationException("Jwt pre-auth code has no expiration time");
}

long now = Time.currentTime();
if (exp < now) {
String message = String.format("Jwt pre-auth code not valid: %s (exp) < %s (now)", exp, now);
throw new VerificationException(message, Errors.EXPIRED_CODE);
}
}

private String getCredentialIssuer() {
return OID4VCIssuerWellKnownProvider.getIssuer(session.getContext());
}

private String getTokenEndpoint() {
WellKnownProvider oidcProvider = session.getProvider(
WellKnownProvider.class, OIDCWellKnownProviderFactory.PROVIDER_ID);
OIDCConfigurationRepresentation oidcConfig = (OIDCConfigurationRepresentation) oidcProvider.getConfig();
return oidcConfig.getTokenEndpoint();
}

@Override
public void close() {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package org.keycloak.protocol.oid4vc.issuance.credentialoffer.preauth;

import org.keycloak.models.KeycloakSession;

public class JwtPreAuthCodeHandlerFactory implements PreAuthCodeHandlerFactory {

public static final String PROVIDER_ID = "jwt-pre-auth-code-handler";


@Override
public String getId() {
return PROVIDER_ID;
}

@Override
public JwtPreAuthCodeHandler create(KeycloakSession session) {
return new JwtPreAuthCodeHandler(session);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package org.keycloak.protocol.oid4vc.issuance.credentialoffer.preauth;

import org.keycloak.common.VerificationException;
import org.keycloak.protocol.oid4vc.model.PreAuthCodeCtx;
import org.keycloak.provider.Provider;

/**
* Handles the production and verification of pre-authorized codes.
*/
public interface PreAuthCodeHandler extends Provider {

/**
* Generates a pre-authorized code for a given context of non-sensitive fields.
* The implementation is responsible for embedding this context so it is recovered with verification.
*/
String createPreAuthCode(PreAuthCodeCtx ctx);

/**
* Verifies the given pre-authorized code and returns its associated context if valid.
*/
PreAuthCodeCtx verifyPreAuthCode(String preAuthCode) throws VerificationException;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package org.keycloak.protocol.oid4vc.issuance.credentialoffer.preauth;

import org.keycloak.Config;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.provider.ProviderFactory;

public interface PreAuthCodeHandlerFactory extends ProviderFactory<PreAuthCodeHandler> {

@Override
default void init(Config.Scope config) {
}

@Override
default void postInit(KeycloakSessionFactory factory) {
}

@Override
default void close() {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package org.keycloak.protocol.oid4vc.issuance.credentialoffer.preauth;

import org.keycloak.provider.Provider;
import org.keycloak.provider.ProviderFactory;
import org.keycloak.provider.Spi;

/**
* SPI for handling the production and verification of pre-authorized codes.
*/
public class PreAuthCodeHandlerSpi implements Spi {

private static final String NAME = "preAuthCodeHandler";

@Override
public boolean isInternal() {
return true;
}

@Override
public String getName() {
return NAME;
}

@Override
public Class<? extends Provider> getProviderClass() {
return PreAuthCodeHandler.class;
}

@Override
public Class<? extends ProviderFactory<PreAuthCodeHandler>> getProviderFactoryClass() {
return PreAuthCodeHandlerFactory.class;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@
import org.keycloak.representations.JsonWebToken;
import org.keycloak.saml.RandomSecret;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jboss.logging.Logger;

/**
* @author Pascal Knüppel
Expand All @@ -63,7 +62,7 @@ public class JwtCNonceHandler implements CNonceHandler {

public static final int NONCE_LENGTH_RANDOM_OFFSET = 15;

private static final Logger logger = LoggerFactory.getLogger(JwtCNonceHandler.class);
private static final Logger logger = Logger.getLogger(JwtCNonceHandler.class);

private final KeycloakSession keycloakSession;

Expand Down Expand Up @@ -189,7 +188,7 @@ protected KeyWrapper selectSigningKey(RealmModel realm) {
try {
signingKey = keycloakSession.keys().getActiveKey(realm, KeyUse.SIG, Algorithm.ES256);
} catch (RuntimeException ex) {
logger.debug("Failed to find active ES256 signing key for realm {}. Falling back to RSA...",
logger.debugf("Failed to find active ES256 signing key for realm %s. Falling back to RSA...",
realm.getName());
logger.debug(ex.getMessage(), ex);
// use RSA only as fallback since the preferred algorithm by OpenID4VC is elliptic curve
Expand Down
Loading
Loading
0