8000 [OID4VCI] User self-issued credential: Issuance initiated from web po… by mposolda · Pull Request #46327 · 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 @@ -26,6 +26,7 @@

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
Expand Down Expand Up @@ -139,6 +140,7 @@ public <T extends AuthorizationDetailsJSONRepresentation> T asSubtype(Class<T> c
return AuthorizationDetailsParser.parseToSubtype(this, clazz);
}

@JsonIgnore
public String getScopeNameFromCustomData() {
if (this.getType().equalsIgnoreCase(DYNAMIC_SCOPE_RAR_TYPE) || this.getType().equalsIgnoreCase(STATIC_SCOPE_RAR_TYPE)) {
List<String> accessList = (List<String>) this.customData.get("access");
Expand All @@ -150,6 +152,7 @@ public String getScopeNameFromCustomData() {
return null;
}

@JsonIgnore
public String getDynamicScopeParamFromCustomData() {
if(this.getType().equalsIgnoreCase(DYNAMIC_SCOPE_RAR_TYPE)) {
return (String) this.customData.get("scope_parameter");
Expand Down
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ public final class OID4VCIConstants {
public static final RoleRepresentation CREDENTIAL_OFFER_CREATE =
new RoleRepresentation("credential-offer-create", "Allow credential offer creation", false);

// Required-action provider ID
public static final String VERIFIABLE_CREDENTIAL_OFFER_PROVIDER_ID = "verifiable_credential_offer";
public static final String CREDENTIAL_CONFIGURATION_ID = "credential_configuration_id";
public static final String CLIENT_ID = "client_id";
public static final String PRE_AUTHORIZED = "pre_authorized";

// authenticationSession note with the stored handle for the credential-offer
public static final String CREDENTIAL_OFFER_NONCE = "credential_offer_nonce";

private OID4VCIConstants() {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -192,10 +192,12 @@ public enum EventType implements EnumWithStableIndex {

VERIFIABLE_CREDENTIAL_REQUEST(62, true),
VERIFIABLE_CREDENTIAL_REQUEST_ERROR(0x10000 + VERIFIABLE_CREDENTIAL_REQUEST.getStableIndex(), true),
VERIFIABLE_CREDENTIAL_OFFER_REQUEST(63, false),
VERIFIABLE_CREDENTIAL_OFFER_REQUEST_ERROR(0x10000 + VERIFIABLE_CREDENTIAL_OFFER_REQUEST.getStableIndex(), false),
VERIFIABLE_CREDENTIAL_OFFER_REQUEST(63, true),
VERIFIABLE_CREDENTIAL_OFFER_REQUEST_ERROR(0x10000 + VERIFIABLE_CREDENTIAL_OFFER_REQUEST.getStableIndex(), true),
VERIFIABLE_CREDENTIAL_NONCE_REQUEST(64, false),
VERIFIABLE_CREDENTIAL_NONCE_REQUEST_ERROR(0x10000 + VERIFIABLE_CREDENTIAL_NONCE_REQUEST.getStableIndex(), false),
VERIFIABLE_CREDENTIAL_CREATE_OFFER(65, true),
VERIFIABLE_CREDENTIAL_CREATE_OFFER_ERROR(0x10000 + VERIFIABLE_CREDENTIAL_CREATE_OFFER.getStableIndex(), true),

JWT_AUTHORIZATION_GRANT(70, true),
JWT_AUTHORIZATION_GRANT_ERROR(0x10000 + JWT_AUTHORIZATION_GRANT.getStableIndex(), true),
Expand Down
< 8 /tr> 10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.keycloak.models.UserModel;

import static org.keycloak.common.Profile.isFeatureEnabled;
import static org.keycloak.constants.OID4VCIConstants.VERIFIABLE_CREDENTIAL_OFFER_PROVIDER_ID;

/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
Expand Down Expand Up @@ -84,7 +85,8 @@ public enum Action {
WEBAUTHN_REGISTER("webauthn-register", DefaultRequiredActions::addWebAuthnRegisterAction, () -> isFeatureEnabled(Profile.Feature.WEB_AUTHN)),
WEBAUTHN_PASSWORDLESS_REGISTER("webauthn-register-passwordless", DefaultRequiredActions::addWebAuthnPasswordlessRegisterAction, () -> isFeatureEnabled(Profile.Feature.WEB_AUTHN)),
VERIFY_USER_PROFILE(UserModel.RequiredAction.VERIFY_PROFILE.name(), DefaultRequiredActions::addVerifyProfile),
IDP_LINK_ACCOUNT("idp_link", DefaultRequiredActions::addIdpLink);
IDP_LINK_ACCOUNT("idp_link", DefaultRequiredActions::addIdpLink),
VERIFIABLE_CREDENTIAL_OFFER(VERIFIABLE_CREDENTIAL_OFFER_PROVIDER_ID, DefaultRequiredActions::addVerifiableCredentialOfferAction, () -> isFeatureEnabled(Profile.Feature.OID4VC_VCI));

private final String alias;
private final Consumer<RealmModel> addAction;
Expand Down Expand Up @@ -237,6 +239,25 @@ public static void addIdpLink(RealmModel realm) {
}
}

public static void addVerifiableCredentialOfferAction(RealmModel realm) {
final boolean isAvailable = Action.VERIFIABLE_CREDENTIAL_OFFER.isAvailable();
if (!isAvailable) return;

final RequiredActionProviderModel provider = realm.getRequiredActionProviderByAlias(VERIFIABLE_CREDENTIAL_OFFER_PROVIDER_ID);
final boolean isRequiredActionActive = provider != null;

if (!isRequiredActionActive) {
RequiredActionProviderModel vc = new RequiredActionProviderModel();
vc.setEnabled(true);
vc.setAlias(VERIFIABLE_CREDENTIAL_OFFER_PROVIDER_ID);
vc.setName("Verifiable Credential Offer");
vc.setProviderId(VERIFIABLE_CREDENTIAL_OFFER_PROVIDER_ID);
vc.setDefaultAction(false);
vc.setPriority(130);
realm.addRequiredActionProvider(vc);
}
}

public static void addUpdateLocaleAction(RealmModel realm) {
if (realm.getRequiredActionProviderByAlias("update_user_locale") == null) {
RequiredActionProviderModel updateUserLocale = new RequiredActionProviderModel();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@

package org.keycloak.protocol.oid4vc.issuance;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.PublicKey;
import java.time.Instant;
import java.util.ArrayList;
Expand Down Expand Up @@ -108,6 +105,7 @@
import org.keycloak.protocol.oid4vc.model.VerifiableCredential;
import org.keycloak.protocol.oid4vc.utils.ClaimsPathPointer;
import org.keycloak.protocol.oid4vc.utils.CredentialScopeModelUtils;
import org.keycloak.protocol.oid4vc.utils.OID4VCUtil;
import org.keycloak.protocol.oidc.grants.PreAuthorizedCodeGrantType;
import org.keycloak.protocol.oidc.rar.AuthorizationDetailsProcessor;
import org.keycloak.representations.AccessToken;
Expand All @@ -123,13 +121,10 @@
import org.keycloak.util.JsonSerialization;
import org.keycloak.util.Strings;
import org.keycloak.utils.MediaType;
import org.keycloak.utils.QRCodeUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpOptions;
Expand Down Expand Up @@ -171,7 +166,7 @@ public class OID4VCIssuerEndpoint {
*/
private AuthenticationManager.AuthResult cachedAuthResult;

private static final String CODE_LIFESPAN_REALM_ATTRIBUTE_KEY = "preAuthorizedCodeLifespanS";
public static final String CODE_LIFESPAN_REALM_ATTRIBUTE_KEY = "preAuthorizedCodeLifespanS";
public static final int DEFAULT_CODE_LIFESPAN_S = 30;

public static final String DEFLATE_COMPRESSION = "DEF";
Expand Down Expand Up @@ -488,7 +483,7 @@ public Response createCredentialOffer(
try {

CredentialOfferProvider offerProvider = session.getProvider(CredentialOfferProvider.class);
offerState = offerProvider.createCredentialOffer(userSession, grantType,
offerState = offerProvider.createCredentialOffer(loginUserModel, grantType,
credentialConfigurationIds, targetClientId, targetUser, expiresAt);

} catch (CredentialOfferException ex) {
Expand Down Expand Up @@ -537,14 +532,9 @@ public Response createCredentialOffer(
}

private byte[] generateQrCode(CredentialOfferURI credOfferURI, int width, int height) {
String encodedOfferUri = URLEncoder.encode(credOfferURI.getCredentialOfferUri(), StandardCharsets.UTF_8);
String offerUri = OID4VCUtil.getOfferAsUri(session, credOfferURI.getNonce());
try {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
String contents = "openid-credential-offer://?credential_offer_uri=" + encodedOfferUri;
BitMatrix bitMatrix = qrCodeWriter.encode(contents, BarcodeFormat.QR_CODE, width, height);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "png", bos);
return bos.toByteArray();
return QRCodeUtils.encodeAsQRBytes(offerUri, width, height);
} catch (WriterException | IOException e) {
String msg = String.format("Cannot create a qr code of dimension %s:%s", width, height);
throw new IllegalStateException(msg, e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

import java.util.List;

import org.keycloak.models.UserSessionModel;
import org.keycloak.models.UserModel;
import org.keycloak.provider.Provider;

/**
Expand Down Expand Up @@ -76,7 +76,7 @@
public interface CredentialOfferProvider extends Provider {

CredentialOfferState createCredentialOffer(
UserSessionModel userSession,
UserModel user,
String grantType,
List<String> credentialConfigurationIds,
String targetClientId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.oid4vci.CredentialScopeModel;
import org.keycloak.protocol.oid4vc.issuance.CredentialOfferException;
import org.keycloak.protocol.oid4vc.issuance.OID4VCIssuerWellKnownProvider;
Expand Down Expand Up @@ -55,7 +54,7 @@ class DefaultCredentialOfferProvider implements CredentialOfferProvider {

@Override
public CredentialOfferState createCredentialOffer(
UserSessionModel userSession,
UserModel user,
String grantType,
List<String> credentialConfigurationIds,
String targetClientId,
Expand All @@ -68,10 +67,12 @@ public CredentialOfferState createCredentialOffer(
throw new CredentialOfferException(Errors.INVALID_REQUEST, "No credentialConfigurationIds");
}

RealmModel realmModel = this.session.getContext().getRealm();

// Validate the target user
//
String targetUserId = Optional.ofNullable(targetUsername)
.map(tu -> validateTargetUser(session, userSession, tu))
.map(tu -> validateTargetUser(session, realmModel, user, tu))
.map(UserModel::getId).orElse(null);

// Create the CredentialsOffer
Expand All @@ -82,7 +83,6 @@ public CredentialOfferState createCredentialOffer(

// Create the CredentialOfferState
//
RealmModel realmModel = userSession.getRealm();
CredentialOfferState offerState = new CredentialOfferState(credOffer, targetClientId, targetUserId, expireAt, credOffersId -> {
List<OID4VCAuthorizationDetail> authDetails = new ArrayList<>();
for (String credConfigId : credentialConfigurationIds) {
Expand All @@ -109,12 +109,7 @@ public CredentialOfferState createCredentialOffer(

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

private UserModel validateTargetUser(KeycloakSession session, UserSessionModel userSession, String targetUser) {
UserModel loginUserModel = userSession.getUser();

// Verify that the target user exists
//
RealmModel realmModel = userSession.getRealm();
private UserModel validateTargetUser(KeycloakSession session, RealmModel realmModel, UserModel loginUserModel, String targetUser) {
UserModel targetUserModel = session.users().getUserByUsername(realmModel, targetUser);
if (targetUserModel == null) {
throw new CredentialOfferException(Errors.USER_NOT_FOUND, "User not found: " + targetUser);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package org.keycloak.protocol.oid4vc.issuance.requiredactions;

import java.io.IOException;

import org.keycloak.models.KeycloakSession;
import org.keycloak.protocol.oid4vc.utils.OID4VCUtil;
import org.keycloak.utils.QRCodeUtils;

import com.google.zxing.WriterException;

public class CredentialOfferBean {

private final String uri;
private final String qrCode;

public CredentialOfferBean(KeycloakSession session, String nonce) throws WriterException, IOException {
this.uri = OID4VCUtil.getOfferAsUri(session, nonce);
this.qrCode = QRCodeUtils.encodeAsQRString(this.uri, 246, 246);
}

public String getUri() {
return uri;
}

public String getQrCode() {
return qrCode;
}
}
Loading
Loading
0