8000 [OID4VCI] Revisit and fix /credential_offer_uri endpoint by tdiesler · Pull Request #46199 · 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
4 changes: 2 additions & 2 deletions js/apps/account-ui/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export async function requestVCOffer(
credentialsIssuer: CredentialsIssuer,
) {
const response = await request(
"/protocol/oid4vc/credential-offer-uri",
"/protocol/oid4vc/create-credential-offer",
context,
{
searchParams: {
Expand All @@ -113,7 +113,7 @@ export async function requestVCOffer(
new URL(
joinPath(
credentialsIssuer.credential_issuer +
"/protocol/oid4vc/credential-offer-uri",
"/protocol/oid4vc/create-credential-offer",
),
),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ public interface Errors {
String INVALID_FORM = "invalid_form";
String INVALID_CONFIG = "invalid_config";
String EXPIRED_CODE = "expired_code";
String MISSING_TX_CODE = "missing_tx_code";
String INVALID_TX_CODE = "invalid_tx_code";
String INVALID_INPUT = "invalid_input";
String COOKIE_NOT_FOUND = "cookie_not_found";
String ALREADY_LOGGED_IN = "already_logged_in";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.protocol.oid4vc.issuance.credentialoffer.CredentialOfferState;
import org.keycloak.protocol.oid4vc.issuance.credentialoffer.CredentialOfferStorage;
import org.keycloak.protocol.oid4vc.model.Claim;
import org.keycloak.protocol.oid4vc.model.ClaimsDescription;
Expand Down Expand Up @@ -127,7 +128,7 @@ private void createOfferStateForAuthorizationCodeFlow(UserSessionModel userSessi
if (oid4vcDetail.getCredentialIdentifiers() != null && !oid4vcDetail.getCredentialIdentifiers().isEmpty()) {
for (String credentialId : oid4vcDetail.getCredentialIdentifiers()) {
// Check if offer state already exists
CredentialOfferStorage.CredentialOfferState existingState = offerStorage.findOfferStateByCredentialId(session, credentialId);
CredentialOfferState existingState = offerStorage.findOfferStateByCredentialId(session, credentialId);

if (existingState == null) {
// Create a new offer state for authorization code flow
Expand All @@ -137,7 +138,7 @@ private void createOfferStateForAuthorizationCodeFlow(UserSessionModel userSessi

// Use a reasonable expiration time (e.g., 1 hour)
int expiration = Time.currentTime() + 3600;
CredentialOfferStorage.CredentialOfferState offerState = new CredentialOfferStorage.CredentialOfferState(
CredentialOfferState offerState = new CredentialOfferState(
credOffer, client.getClientId(), user.getId(), expiration);
offerState.setAuthorizationDetails(oid4vcDetail);

Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* 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.beans.Transient;
import java.security.SecureRandom;
import java.util.Optional;

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.JsonInclude;

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

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

public CredentialOfferState(CredentialsOffer credOffer, String clientId, String userId, int expireAt) {
this.credentialsOffer = credOffer;
this.clientId = clientId;
this.userId = userId;
this.expireAt = expireAt;
this.nonce = Base64Url.encode(RandomSecret.createRandomSecret(64));
}

// For json serialization
CredentialOfferState() {
}

@Transient
public Optional<String> getPreAuthorizedCode() {
return Optional.ofNullable(credentialsOffer.getGrants())
.map(PreAuthorizedGrant::getPreAuthorizedCode)
.map(PreAuthorizedCode::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 CredentialsOffer getCredentialsOffer() {
return credentialsOffer;
}

public String getClientId() {
return clientId;
}

public String getUserId() {
return userId;
}

public String getNonce() {
return nonce;
}

public String getTxCode() {
return txCode;
}

public int getExpireAt() {
return expireAt;
}

public OID4VCAuthorizationDetail getAuthorizationDetails() {
return authorizationDetails;
}

public void setAuthorizationDetails(OID4VCAuthorizationDetail authorizationDetails) {
this.authorizationDetails = authorizationDetails;
}

@Transient
public boolean isExpired() {
return expireAt < Time.currentTime();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,107 +16,11 @@
*/
package org.keycloak.protocol.oid4vc.issuance.credentialoffer;

import java.beans.Transient;
import java.util.Optional;

import org.keycloak.common.util.Base64Url;
import org.keycloak.common.util.Time;
import org.keycloak.models.KeycloakSession;
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.provider.Provider;
import org.keycloak.saml.RandomSecret;

import com.fasterxml.jackson.annotation.JsonInclude;

public interface CredentialOfferStorage extends Provider {

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

private CredentialsOffer credentialsOffer;
private String clientId;
private String userId;
private String nonce;
private int expiration;
private OID4VCAuthorizationDetail authorizationDetails;

public CredentialOfferState(CredentialsOffer credOffer, String clientId, String userId, int expiration) {
this.credentialsOffer = credOffer;
this.clientId = clientId;
this.userId = userId;
this.expiration = expiration;
this.nonce = Base64Url.encode(RandomSecret.createRandomSecret(64));
}

// For json serialization
CredentialOfferState() {
}

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

@Transient
public boolean isExpired() {
int currentTime = Time.currentTime();
return currentTime > expiration;
}

public CredentialsOffer getCredentialsOffer() {
return credentialsOffer;
}

public String getClientId() {
return clientId;
}

public String getUserId() {
return userId;
}

public String getNonce() {
return nonce;
}

public int getExpiration() {
return expiration;
}

public OID4VCAuthorizationDetail getAuthorizationDetails() {
return authorizationDetails;
}

public void setAuthorizationDetails(OID4VCAuthorizationDetail authorizationDetails) {
this.authorizationDetails = authorizationDetails;
}

void setCredentialsOffer(CredentialsOffer credentialsOffer) {
this.credentialsOffer = credentialsOffer;
}

void setClientId(String clientId) {
this.clientId = clientId;
}

void setUserId(String userId) {
this.userId = userId;
}

void setNonce(String nonce) {
this.nonce = nonce;
}

void setExpiration(int expiration) {
this.expiration = expiration;
}
}

void putOfferState(KeycloakSession session, CredentialOfferState entry);

CredentialOfferState findOfferStateByNonce(KeycloakSession session, String nonce);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ private long calculateLifespanSeconds(int expirationTimestamp) {

@Override
public void putOfferState(KeycloakSession session, CredentialOfferState entry) {
long lifespanSeconds = calculateLifespanSeconds(entry.getExpiration());
long lifespanSeconds = calculateLifespanSeconds(entry.getExpireAt());

// Skip storing if already expired (following pattern from InfinispanSingleUseObjectProviderFactory)
if (lifespanSeconds <= 0) {
Expand Down Expand Up @@ -110,7 +110,7 @@ public void replaceOfferState(KeycloakSession session, CredentialOfferState entr
session.singleUseObjects().replace(it, Map.of(ENTRY_KEY, entryJson));
});
Optional.ofNullable(entry.getAuthorizationDetails()).ifPresent(it -> {
long lifespanSeconds = calculateLifespanSeconds(entry.getExpiration());
long lifespanSeconds = calculateLifespanSeconds(entry.getExpireAt());
it.getCredentialIdentifiers().forEach( cid -> {
if (session.singleUseObjects().contains(cid)) {
session.singleUseObjects().replace(cid, Map.of(ENTRY_KEY, entryJson));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

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


/**
Expand All @@ -30,9 +31,16 @@
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CredentialOfferURI {

private String issuer;
private String nonce;

@JsonProperty("tx_code")
private String txCode;

@JsonProperty("qr_code")
private String qrCode;

public String getIssuer() {
return issuer;
}
Expand All @@ -51,6 +59,28 @@ public CredentialOfferURI setNonce(String nonce) {
return this;
}

public String getTxCode() {
return txCode;
}

public CredentialOfferURI setTxCode(String txCode) {
this.txCode = txCode;
return this;
}

public String getQrCode() {
return qrCode;
}

/**
* Encoded QR-Code such that it can be used directly in a web page
* {@code <img src="data:image/png;base64,AAAA..." />}
*/
public CredentialOfferURI setQrCode(String qrCode) {
this.qrCode = qrCode;
return this;
}

@JsonIgnore
public String getCredentialOfferUri() {
return KeycloakUriBuilder.fromUri(issuer).path(nonce).build().toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@
*
* @author <a href="https://github.com/wistefan">Stefan Wiedemann</a>
*/
public enum OfferUriType {
public enum OfferResponseType {

QR("qr"),
URI("uri"),

QR_CODE("qr-code");
URI_AND_QR("uri+qr");

private final String value;

OfferUriType(String value) {
OfferResponseType(String value) {
this.value = value;
}

Expand All @@ -43,15 +43,17 @@ public String getValue() {
}

@JsonCreator
public static OfferUriType fromString(String value) {
public static OfferResponseType fromString(String value) {
return Optional.ofNullable(value)
.map(v -> {
if (v.equals(URI.getValue())) {
if (v.equals(QR.getValue())) {
return QR;
} else if (v.equals(URI.getValue())) {
return URI;
} else if (v.equals(QR_CODE.getValue())) {
return QR_CODE;
} else if (v.equals(URI_AND_QR.getValue())) {
return URI_AND_QR;
} else return null;
})
.orElseThrow(() -> new IllegalArgumentException(String.format("%s is not a supported OfferUriType.", value)));
}
}
}
Loading
Loading
0