Thanks to visit codestin.com
Credit goes to github.com

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
2 changes: 2 additions & 0 deletions core/src/main/java/org/keycloak/OAuth2Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,8 @@ public interface OAuth2Constants {
String ISSUER = "iss";

String AUTHENTICATOR_METHOD_REFERENCE = "amr";

String CNF = "cnf";
}


Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ private RefreshToken() {
/**
* Deep copies issuer, subject, issuedFor, sessionState from AccessToken.
*
* @param token
*/
public RefreshToken(AccessToken token) {
this();
Expand All @@ -49,6 +48,25 @@ public RefreshToken(AccessToken token) {
this.scope = token.scope;
}

/**
* Deep copies issuer, subject, issuedFor, sessionState from AccessToken.
*
* @param token
* @param confirmation optional confirmation parameter that might be processed during authentication but should not
* always be included in the response
*/
public RefreshToken(AccessToken token, Confirmation confirmation) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible if you keep also the constructor with single refresh token argument just for the backwards compatibility? So possibly maybe just something like this:

public RefreshToken(AccessToken token) {
    this(token, null);
}

this();
this.issuer = token.issuer;
this.subject = token.subject;
this.issuedFor = token.issuedFor;
this.sessionId = token.sessionId;
this.nonce = token.nonce;
this.audience = new String[] { token.issuer };
this.scope = token.scope;
this.confirmation = confirmation;
}

@Override
public TokenCategory getCategory() {
return TokenCategory.INTERNAL;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.provider.Provider;
import org.keycloak.representations.dpop.DPoP;
import org.keycloak.services.cors.Cors;

/**
Expand Down Expand Up @@ -72,10 +71,9 @@ public static class Context {
protected EventBuilder event;
protected Cors cors;
protected Object tokenManager;
protected DPoP dPoP;

public Context(KeycloakSession session, Object clientConfig, Map<String, String> clientAuthAttributes,
MultivaluedMap<String, String> formParams, EventBuilder event, Cors cors, Object tokenManager, DPoP dPoP) {
MultivaluedMap<String, String> formParams, EventBuilder event, Cors cors, Object tokenManager) {
this.session = session;
this.realm = session.getContext().getRealm();
this.client = session.getContext().getClient();
Expand All @@ -89,7 +87,6 @@ public Context(KeycloakSession session, Object clientConfig, Map<String, String>
this.event = event;
this.cors = cors;
this.tokenManager = tokenManager;
this.dPoP = dPoP;
}

public Context(Context context) {
Expand All @@ -106,7 +103,6 @@ public Context(Context context) {
this.event = context.event;
this.cors = context.cors;
this.tokenManager = context.tokenManager;
this.dPoP = context.dPoP;
}

public void setFormParams(MultivaluedHashMap<String, String> formParams) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.keycloak.models.UserModel;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.OIDCLoginProtocolFactory;
import org.keycloak.services.util.DPoPUtil;

import java.lang.reflect.Method;
import java.util.AbstractMap;
Expand Down Expand Up @@ -130,16 +131,20 @@ public static Stream<Entry<ProtocolMapperModel, ProtocolMapper>> getSortedProtoc

public static Stream<Entry<ProtocolMapperModel, ProtocolMapper>> getSortedProtocolMappers(KeycloakSession session, ClientSessionContext ctx, Predicate<Entry<ProtocolMapperModel, ProtocolMapper>> filter) {
KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
return ctx.getProtocolMappersStream()
.<Entry<ProtocolMapperModel, ProtocolMapper>>map(mapperModel -> {
ProtocolMapper mapper = (ProtocolMapper) sessionFactory.getProviderFactory(ProtocolMapper.class, mapperModel.getProtocolMapper());
if (mapper == null) {
return null;
}
return new AbstractMap.SimpleEntry<>(mapperModel, mapper);
})
.filter(Objects::nonNull)
.filter(filter)

Stream<Entry<ProtocolMapperModel, ProtocolMapper>> protocolMapperStream = //
ctx.getProtocolMappersStream()
.<Entry<ProtocolMapperModel, ProtocolMapper>>map(mapperModel -> {
ProtocolMapper mapper = (ProtocolMapper) sessionFactory.getProviderFactory(ProtocolMapper.class, mapperModel.getProtocolMapper());
if (mapper == null) {
return null;
}
return new AbstractMap.SimpleEntry<>(mapperModel, mapper);
})
.filter(Objects::nonNull)
.filter(filter);

return Stream.concat(protocolMapperStream, DPoPUtil.getTransientProtocolMapper())
.sorted(Comparator.comparing(ProtocolMapperUtils::compare));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ public Response authenticated(final AuthenticationSessionModel authSession, fina
AtomicReference<DockerResponseToken> finalResponseToken = new AtomicReference<>(responseToken);
ProtocolMapperUtils.getSortedProtocolMappers(session, clientSessionCtx, mapper ->
mapper.getValue() instanceof DockerAuthV2AttributeMapper && ((DockerAuthV2AttributeMapper) mapper.getValue()).appliesTo(finalResponseToken.get()))
.filter(mapper -> mapper instanceof DockerAuthV2AttributeMapper)
.forEach(mapper -> finalResponseToken.set(((DockerAuthV2AttributeMapper) mapper.getValue())
.transformDockerResponseToken(finalResponseToken.get(), mapper.getKey(), session, userSession, clientSession)));
responseToken = finalResponseToken.get();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
import org.keycloak.models.ClientScopeModel;
import org.keycloak.models.ClientSessionContext;
import org.keycloak.models.Constants;
import org.keycloak.models.ImpersonationSessionNote;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
Expand Down Expand Up @@ -959,7 +958,7 @@ protected AccessToken initToken(RealmModel realm, ClientModel client, UserModel
ClientSessionContext clientSessionCtx, UriInfo uriInfo) {
AccessToken token = new AccessToken();
token.id(KeycloakModelUtils.generateId());
token.type(TokenUtil.TOKEN_TYPE_BEARER);
token.type(formatTokenType(client, token));
if (UserSessionModel.SessionPersistenceState.TRANSIENT.equals(session.getPersistenceState())) {
token.subject(user.getId());
}
Expand Down Expand Up @@ -1061,7 +1060,7 @@ public AccessTokenResponseBuilder(RealmModel realm, ClientModel client, EventBui
this.session = session;
this.userSession = userSession;
this.clientSessionCtx = clientSessionCtx;
this.responseTokenType = formatTokenType(client);
this.responseTokenType = formatTokenType(client, null);
}

public AccessToken getAccessToken() {
Expand All @@ -1078,6 +1077,7 @@ public IDToken getIdToken() {

public AccessTokenResponseBuilder accessToken(AccessToken accessToken) {
this.accessToken = accessToken;
this.responseTokenType = formatTokenType(client, accessToken);
return this;
}
public AccessTokenResponseBuilder refreshToken(RefreshToken refreshToken) {
Expand All @@ -1098,6 +1098,7 @@ public AccessTokenResponseBuilder offlineToken(boolean offlineToken) {
public AccessTokenResponseBuilder generateAccessToken() {
UserModel user = userSession.getUser();
accessToken = createClientAccessToken(session, realm, client, user, userSession, clientSessionCtx);
responseTokenType = formatTokenType(client, accessToken);
return this;
}

Expand Down Expand Up @@ -1136,10 +1137,11 @@ public AccessTokenResponseBuilder generateRefreshToken(RefreshToken oldRefreshTo
}

private void generateRefreshToken(boolean offlineTokenRequested) {
refreshToken = new RefreshToken(accessToken);
AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();
final AccessToken.Confirmation confirmation = getConfirmation(clientSession, accessToken);
refreshToken = new RefreshToken(accessToken, confirmation);
refreshToken.id(KeycloakModelUtils.generateId());
refreshToken.issuedNow();
AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();
clientSession.setTimestamp(refreshToken.getIat().intValue());
UserSessionModel userSession = clientSession.getUserSession();
userSession.setLastSessionRefresh(refreshToken.getIat().intValue());
Expand All @@ -1160,6 +1162,19 @@ private void generateRefreshToken(boolean offlineTokenRequested) {
}
}

/**
* RFC9449 chapter 5<br/>
* Refresh tokens issued to confidential clients are not bound to the DPoP proof public key because
* they are already sender-constrained with a different existing mechanism.<br/>
* <br/>
* Based on the definition above the confirmation is only returned for public-clients.
*/
private AccessToken.Confirmation getConfirmation(AuthenticatedClientSessionModel clientSession,
AccessToken accessToken) {
final boolean isPublicClient = clientSession.getClient().isPublicClient();
return isPublicClient ? accessToken.getConfirmation() : null;
}

private Long getExpiration(boolean offline) {
long expiration = SessionExpirationUtils.calculateClientSessionIdleTimestamp(
offline, userSession.isRememberMe(),
Expand Down Expand Up @@ -1314,11 +1329,13 @@ private String generateOIDCHash(String input) {

}

private String formatTokenType(ClientModel client) {
private String formatTokenType(ClientModel client, AccessToken accessToken) {
final String tokenType = Optional.ofNullable(accessToken).map(AccessToken::getType)
.orElse(TokenUtil.TOKEN_TYPE_BEARER);
if (OIDCAdvancedConfigWrapper.fromClientModel(client).isUseLowerCaseInTokenResponse()) {
return TokenUtil.TOKEN_TYPE_BEARER.toLowerCase();
return tokenType.toLowerCase();
}
return TokenUtil.TOKEN_TYPE_BEARER;
return tokenType;
}

public static class NotBeforeCheck implements TokenVerifier.Predicate<JsonWebToken> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,14 @@
import org.keycloak.protocol.saml.JaxrsSAML2BindingBuilder;
import org.keycloak.protocol.saml.SamlClient;
import org.keycloak.protocol.saml.SamlProtocol;
import org.keycloak.representations.dpop.DPoP;
import org.keycloak.saml.common.constants.JBossSAMLConstants;
import org.keycloak.saml.common.constants.JBossSAMLURIConstants;
import org.keycloak.saml.common.exceptions.ConfigurationException;
import org.keycloak.saml.common.exceptions.ProcessingException;
import org.keycloak.saml.common.util.DocumentUtil;
import org.keycloak.services.CorsErrorResponseException;
import org.keycloak.services.cors.Cors;
import org.keycloak.services.util.DPoPUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

Expand All @@ -73,7 +73,6 @@ public class TokenEndpoint {
private ClientModel client;
private Map<String, String> clientAuthAttributes;
private OIDCAdvancedConfigWrapper clientConfig;
private DPoP dPoP;

private final KeycloakSession session;

Expand Down Expand Up @@ -136,7 +135,19 @@ public Response processGrantRequest() {
checkParameterDuplicated();
}

OAuth2GrantType.Context context = new OAuth2GrantType.Context(session, clientConfig, clientAuthAttributes, formParams, event, cors, tokenManager, dPoP);
/*
* To request an access token that is bound to a public key using DPoP, the client MUST provide a valid DPoP
* proof JWT in a DPoP header when making an access token request to the authorization server's token endpoint.
* This is applicable for all access token requests regardless of grant type (e.g., the common
* authorization_code and refresh_token grant types and extension grants such as the JWT
* authorization grant [RFC7523])
*/
DPoPUtil.retrieveDPoPHeaderIfPresent(session, clientConfig, event, cors).ifPresent(dPoP -> {
session.setAttribute(DPoPUtil.DPOP_SESSION_ATTRIBUTE, dPoP);
});

OAuth2GrantType.Context context = new OAuth2GrantType.Context(session, clientConfig, clientAuthAttributes,
formParams, event, cors, tokenManager);
return grant.process(context);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,13 @@

import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException;
import org.keycloak.common.Profile;
import org.keycloak.common.util.KeycloakUriBuilder;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventType;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.ClientScopeModel;
import org.keycloak.models.ClientSessionContext;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
Expand Down Expand Up @@ -63,8 +61,6 @@ public class AuthorizationCodeGrantType extends OAuth2GrantTypeBase {
public Response process(Context context) {
setContext(context);

checkAndRetrieveDPoPProof(Profile.isFeatureEnabled(Profile.Feature.DPOP));

String code = formParams.getFirst(OAuth2Constants.CODE);
if (code == null) {
String errorMessage = "Missing parameter: " + OAuth2Constants.CODE;
Expand Down
Loading