8000 [OID4VCI] Add support for credential scope policies by tdiesler · Pull Request #46466 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
8000
Closed
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
3 changes: 3 additions & 0 deletions core/src/main/java/org/keycloak/OAuth2Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -174,4 +174,7 @@ public interface OAuth2Constants {
String DPOP_JWT_HEADER_TYPE = "dpop+jwt";
String ALGS_ATTRIBUTE = "algs";

// OID4VCI - https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html#section-5.1.3
// Used to pass the issuer_state value back to the Credential Issuer.
String ISSUER_STATE = "issuer_state";
}
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -136,19 +136,6 @@ public class CredentialScopeModel implements ClientScopeModel {
*/
public static final String VC_KEY_ATTESTATION_REQUIRED_USER_AUTH = "vc.key_attestations_required.user_authentication";

// [TODO] Remove deprecated constants used in the old testsuite
@Deprecated public static final String CONFIGURATION_ID = VC_CONFIGURATION_ID;
@Deprecated public static final String CREDENTIAL_IDENTIFIER = VC_IDENTIFIER;
@Deprecated public static final String CONTEXTS = VC_CONTEXTS;
@Deprecated public static final String EXPIRY_IN_SECONDS = VC_EXPIRY_IN_SECONDS;
@Deprecated public static final Integer EXPIRY_IN_SECONDS_DEFAULT = VC_EXPIRY_IN_SECONDS_DEFAULT;
@Deprecated public static final String FORMAT = VC_FORMAT;
@Deprecated public static final String ISSUER_DID = VC_ISSUER_DID;
@Deprecated public static final String KEY_ATTESTATION_REQUIRED = VC_KEY_ATTESTATION_REQUIRED;
@Deprecated public static final String KEY_ATTESTATION_REQUIRED_KEY_STORAGE = VC_KEY_ATTESTATION_REQUIRED_KEY_STORAGE;
@Deprecated public static final String KEY_ATTESTATION_REQUIRED_USER_AUTH = VC_KEY_ATTESTATION_REQUIRED_USER_AUTH;
@Deprecated public static final String TYPES = VC_SUPPORTED_TYPES;

/**
* the actual object that is represented by this scope
*/
Expand All @@ -172,7 +159,7 @@ public String getScope() {
}

public String getCredentialConfigurationId() {
return clientScope.getAttribute(VC_CONFIGURATION_ID);
return Optional.ofNullable(clientScope.getAttribute(VC_CONFIGURATION_ID)).orElse(clientScope.getName());
}

public void setCredentialConfigurationId(String credentialConfigurationId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,6 @@ public enum ClientPolicyEvent {

SAML_AUTHN_REQUEST,
SAML_LOGOUT_REQUEST,

CREDENTIAL_OFFER_CREATE
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright 2025 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.protocol.oid4vc.issuance;

public class CredentialOfferException extends RuntimeException {

private final String errorType;

public CredentialOfferException(String errorType, String message) {
this(errorType, message, null);
}

public CredentialOfferException(String errorType, String message, Throwable cause) {
super(message, cause);
this.errorType = errorType;

}

public String getErrorType() {
return errorType;
}
}

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* Copyright 2025 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.protocol.oid4vc.issuance.credentialoffer;

import java.util.List;

import org.keycloak.models.KeycloakSession;
import org.keycloak.models.UserSessionModel;
import org.keycloak.provider.Provider;
import org.keycloak.services.clientpolicy.ClientPolicyException;

/**
* A provider for OID4VCI Credential Offers.
*
* In principle, it is the Issuer who creates a Credential Offer and then passes it to the Wallet. This can be done
* by {@code credential_offer_uri}, by qr-code (for cross device flows), by a Wallet provided {@code credential_offer_endpoint}
* or by some other means (e.g. email, messaging, etc.).
*
* The spec does not detail how to request a Credential Offer from an Issuer. In Keycloak, we provide an {@code /create-credential-offer}
* endpoint that requires various access privileges depending on the offer that is to be created. Other means to create a
* Credential Offer may exist in the Admin Console.
*
* Depending on Credential Offer Policies for a given {@code credential_configuration_id} and Issuing User, these required
* privileges may be permissible enough to allow for a "self-issued" Credential Offer.
*
* With the Credential Offer the Wallet receives a grant for set of {@code credential_configuration_ids}.
*
* Credential Offers come in two variants
* <ul>
* <li>{@code authorization_code} grant</li>
* <li>{@code pre-authorized_code} grant</li>
* </ul>
*
* <h4>Authorization Code Grant</h4>
*
* With the {@code authorization_code} grant, the Wallet can send an Authorization Request that references one of the
* {@code credential_configuration_ids} in {@code authorization_details}. Part of the {@code authorization_code} grant
* is also some opaque {@code issuer_state} that the Wallet must include in the Authorization Request. This allows the
* Issuer to correlate the Authorization Request with a previously made Credential Offer.
*
* The Wallet may also send an Authorization Request with a {@code scope} parameter and no {@code authorization_details}
* nor {@code issuer_state}. This by-passes the Credential Offer process completely - the Authorization Server may
* still return an Authorization Code, which can then be used in an AccessToken request and ultimately grants access
* to Credentials associated with that {@code scope}.
*
* Whether the Authorization Server grants access or the Credential Endpoint actually returns the wanted Credential again
* depends on the effective Credential Policies. These may require an existing Credential Offer for a given and hence prevent
* such a Credential Request on scope alone.
*
* <h4>Pre-Authorized Code Grant</h4>
*
* As the name suggests, this is a "pre-authorized" grant that the Wallet can use directly in an AccessToken Request. No
* further authorization is required on part of the Wallet. It works for cases where the Wallet cannot be expected to use
* an {@code authorization_code} grant. Since this is bearer grant that gives direct access to the Credentials referenced
* by {@code credential_configuration_ids}, the party that creates such a Credential Offer must take upmost be care about
* how to communicate that "pre-authorized" grant. As a second authorization factor, the Issuer can create a {@code tx_code}
* together with the Credential Offer. The {@code tx_code} is to be communicated via an alternative channel
* (i.e. not together with the pre-authorized code).
*
* https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html#name-credential-offer
*
* @author <a href="mailto:tdiesler@ibm.com">Thomas Diesler</a>
*/
public interface CredentialOfferProvider extends Provider {

CredentialOfferState createCredentialOffer(
KeycloakSession session,
UserSessionModel userSession,
String grantType,
List<String> credentialConfigurationIds,
String targetClientId,
String targetUserId,
Boolean withTxCode,
Integer expireAt
) throws ClientPolicyException;

@Override
default void close() {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright 2025 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.protocol.oid4vc.issuance.credentialoffer;

import org.keycloak.provider.ProviderFactory;

/**
* @author <a href="mailto:tdiesler@ibm.com">Thomas Diesler</a>
*/
public interface CredentialOfferProviderFactory extends ProviderFactory<CredentialOfferProvider> {

@Override
default void close() { }

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright 2025 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.protocol.oid4vc.issuance.credentialoffer;

import org.keycloak.provider.Spi;

/**
* @author <a href="mailto:tdiesler@ibm.com">Thomas Diesler</a>
*/
public class CredentialOfferProviderSpi implements Spi {
@Override public String getName() { return "credential-offer-provider"; }
@Override public Class<CredentialOfferProvider> getProviderClass() { return CredentialOfferProvider.class; }
@Override public Class<CredentialOfferProviderFactory> getProviderFactoryClass() { return CredentialOfferProviderFactory.class; }
@Override public boolean isInternal() { return false; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,70 +16,87 @@
*/
package org.keycloak.protocol.oid4vc.issuance.credentialoffer;

import java.beans.Transient;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import org.keycloak.common.util.Base64Url;
import org.keycloak.common.util.Time;
import org.keycloak.protocol.oid4vc.model.CredentialsOffer;
import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail;
import org.keycloak.protocol.oid4vc.model.PreAuthorizedCode;
import org.keycloak.protocol.oid4vc.model.PreAuthorizedGrant;
import org.keycloak.saml.RandomSecret;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;


@JsonInclude(JsonInclude.Include.NON_NULL)
public class CredentialOfferState {

private String credentialsOfferId;
private CredentialsOffer credentialsOffer;
private String clientId;
private String userId;
private String targetClientId;
private String targetUserId;
private String nonce;
private String txCode;
private int expireAt;
private OID4VCAuthorizationDetail authorizationDetails;

public CredentialOfferState(CredentialsOffer credOffer, String clientId, String userId, int expireAt) {
private List<OID4VCAuthorizationDetail> authDetails;

/**
* Create a new CredentialOfferState.
* <p>
* This should only be called from the configured {@code CredentialOfferProvider}.
* The constructor is public for testing purposes only.
*
* @param credOffer The credential offer
* @param clientId The target client_id
* @param userId The target user id
* @param withTxCode A flag to indicate whether a tx_code should be generated
* @param expireAt The expiry date of the offer in seconds
* @param authDetails The list of authorization details, (optionally) one for each credential_configuration_id
*/
public CredentialOfferState(
CredentialsOffer credOffer,
String clientId,
String userId,
boolean withTxCode,
int expireAt,
List<OID4VCAuthorizationDetail> authDetails
) {
this.credentialsOfferId = UUID.randomUUID().toString();
this.credentialsOffer = credOffer;
this.clientId = clientId;
this.userId = userId;
this.targetClientId = clientId;
this.targetUserId = userId;
this.expireAt = expireAt;
this.nonce = Base64Url.encode(RandomSecret.createRandomSecret(64));
}
this.authDetails = authDetails != null ? Collections.unmodifiableList(authDetails) : List.of();

// For json serialization
CredentialOfferState() {
if (withTxCode) {
this.txCode = generateTxCode();
}
}

@Transient
@JsonIgnore
public Optional<String> getPreAuthorizedCode() {
return Optional.ofNullable(credentialsOffer.getGrants())
.map(PreAuthorizedGrant::getPreAuthorizedCode)
.map(PreAuthorizedCode::getPreAuthorizedCode);
return Optional.ofNullable(credentialsOffer.getPreAuthorizedCode());
}

public void generateTxCode() {
SecureRandom rnd = new SecureRandom();
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
StringBuilder sb = new StringBuilder(6);
for (int i = 0; i < 6; i++) {
sb.append(alphabet[rnd.nextInt(alphabet.length)]);
}
txCode = sb.toString();
public String getCredentialsOfferId() {
return credentialsOfferId;
}

public CredentialsOffer getCredentialsOffer() {
return credentialsOffer;
}

public String getClientId() {
return clientId;
public String getTargetClientId() {
return targetClientId;
}

public String getUserId() {
return userId;
public String getTargetUserId() {
return targetUserId;
}

public String getNonce() {
Expand All @@ -94,16 +111,41 @@ public int getExpireAt() {
return expireAt;
}

public OID4VCAuthorizationDetail getAuthorizationDetails() {
return authorizationDetails;
public List<OID4VCAuthorizationDetail> getAuthorizationDetails() {
return authDetails;
}

public void setAuthorizationDetails(OID4VCAuthorizationDetail authorizationDetails) {
this.authorizationDetails = authorizationDetails;
public OID4VCAuthorizationDetail getAuthorizationDetails(String credConfigId) {
return authDetails.stream()
.filter(it -> it.getCredentialConfigurationId().equals(credConfigId))
.findFirst()
.map(OID4VCAuthorizationDetail::clone)
.orElse(null);
}

@Transient
@JsonIgnore
public boolean isExpired() {
return expireAt < Time.currentTime();
}

// Private ---------------------------------------------------------------------------------------------------------

// For json serialization
private CredentialOfferState() {
}

// For json serialization
private void setAuthorizationDetails(List<OID4VCAuthorizationDetail> authDetails) {
this.authDetails = authDetails;
}

private String generateTxCode() {
SecureRandom rnd = new SecureRandom();
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
StringBuilder sb = new StringBuilder(6);
for (int i = 0; i < 6; i++) {
sb.append(alphabet[rnd.nextInt(alphabet.length)]);
}
return sb.toString();
}
}
Loading
Loading
0