OAuth 2.0 Grant Type SPI

Closes: #26250

Signed-off-by: Dmitry Telegin <demetrio@carretti.pro>
This commit is contained in:
Dmitry Telegin 2023-12-13 02:44:59 +00:00 committed by Pedro Igor
parent dfd3fee95a
commit 983680ce0e
15 changed files with 1622 additions and 856 deletions

View file

@ -0,0 +1,122 @@
/*
* Copyright 2024 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.oidc.grants;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import java.util.Map;
import org.keycloak.common.ClientConnection;
import org.keycloak.events.EventBuilder;
import org.keycloak.events.EventType;
import org.keycloak.http.HttpRequest;
import org.keycloak.http.HttpResponse;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.provider.Provider;
import org.keycloak.provider.ProviderFactory;
import org.keycloak.representations.dpop.DPoP;
/**
* Provider interface for OAuth 2.0 grant types
*
* @author <a href="mailto:demetrio@carretti.pro">Dmitry Telegin</a>
*/
public interface OAuth2GrantType extends Provider, ProviderFactory<OAuth2GrantType> {
/**
* Returns EventType associated with this grant type
*
* @return event type
*/
EventType getEventType();
/**
* Returns the name of the OAuth 2.0 grant type implemented by this provider.
* This value will be matched against the "grant_type" token request parameter.
*
* @return grant type name
*/
String getGrantType();
/**
* Processes grant request.
* @param context grant request context
* @return token response
*/
Response process(Context context);
public static class Context {
protected KeycloakSession session;
protected RealmModel realm;
protected ClientModel client;
protected Object clientConfig;
protected ClientConnection clientConnection;
protected Map<String, String> clientAuthAttributes;
protected HttpRequest request;
protected HttpResponse response;
protected HttpHeaders headers;
protected MultivaluedMap<String, String> formParams;
protected EventBuilder event;
protected Object cors;
protected Object tokenManager;
protected DPoP dPoP;
public Context(KeycloakSession session, RealmModel realm,
ClientModel client, Object clientConfig, ClientConnection clientConnection, Map<String, String> clientAuthAttributes,
HttpRequest request, HttpResponse response, HttpHeaders headers, MultivaluedMap<String, String> formParams,
EventBuilder event, Object cors, Object tokenManager, DPoP dPoP) {
this.session = session;
this.realm = realm;
this.client = client;
this.clientConfig = clientConfig;
this.clientConnection = clientConnection;
this.clientAuthAttributes = clientAuthAttributes;
this.request = request;
this.response = response;
this.headers = headers;
this.formParams = formParams;
this.event = event;
this.cors = cors;
this.tokenManager = tokenManager;
this.dPoP = dPoP;
}
public Context(Context context) {
this.session = context.session;
this.realm = context.realm;
this.client = context.client;
this.clientConfig = context.clientConfig;
this.clientConnection = context.clientConnection;
this.clientAuthAttributes = context.clientAuthAttributes;
this.request = context.request;
this.response = context.response;
this.headers = context.headers;
this.formParams = context.formParams;
this.event = context.event;
this.cors = context.cors;
this.tokenManager = context.tokenManager;
this.dPoP = context.dPoP;
}
}
}

View file

@ -0,0 +1,53 @@
/*
* Copyright 2024 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.oidc.grants;
import org.keycloak.provider.Provider;
import org.keycloak.provider.ProviderFactory;
import org.keycloak.provider.Spi;
/**
* <p>A {@link Spi} to support pluggable OAuth 2.0 grant types in Token Endpoint.
*
* @author <a href="mailto:demetrio@carretti.pro">Dmitry Telegin</a>
*/
public class OAuth2GrantTypeSpi implements Spi {
private static final String SPI_NAME = "oauth2-grant-type";
@Override
public boolean isInternal() {
return true;
}
@Override
public String getName() {
return SPI_NAME;
}
@Override
public Class<? extends Provider> getProviderClass() {
return OAuth2GrantType.class;
}
@Override
public Class<? extends ProviderFactory> getProviderFactoryClass() {
return OAuth2GrantType.class;
}
}

View file

@ -70,6 +70,7 @@ org.keycloak.deployment.DeployedConfigurationsSpi
org.keycloak.models.cache.authorization.CachedStoreFactorySpi
org.keycloak.protocol.oidc.TokenExchangeSpi
org.keycloak.protocol.oidc.TokenIntrospectionSpi
org.keycloak.protocol.oidc.grants.OAuth2GrantTypeSpi
org.keycloak.protocol.saml.ArtifactResolverSpi
org.keycloak.policy.PasswordPolicySpi
org.keycloak.policy.PasswordPolicyManagerSpi

View file

@ -22,51 +22,24 @@ import org.keycloak.http.HttpRequest;
import org.keycloak.http.HttpResponse;
import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException;
import org.keycloak.authentication.AuthenticationProcessor;
import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.authorization.AuthorizationTokenService;
import org.keycloak.authorization.util.Tokens;
import org.keycloak.common.ClientConnection;
import org.keycloak.common.Profile;
import org.keycloak.common.VerificationException;
import org.keycloak.common.constants.ServiceAccountConstants;
import org.keycloak.common.util.KeycloakUriBuilder;
import org.keycloak.constants.AdapterConstants;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventBuilder;
import org.keycloak.events.EventType;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.JWSInputException;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.AuthenticationFlowModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientScopeModel;
import org.keycloak.models.ClientSessionContext;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.utils.AuthenticationFlowResolver;
import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.TokenExchangeContext;
import org.keycloak.protocol.oidc.TokenExchangeProvider;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.protocol.oidc.grants.ciba.CibaGrantType;
import org.keycloak.protocol.oidc.grants.device.DeviceGrantType;
import org.keycloak.protocol.oidc.grants.OAuth2GrantManager;
import org.keycloak.protocol.oidc.grants.OAuth2GrantType;
import org.keycloak.protocol.oidc.utils.AuthorizeClientUtil;
import org.keycloak.protocol.oidc.utils.OAuth2Code;
import org.keycloak.protocol.oidc.utils.OAuth2CodeParser;
import org.keycloak.protocol.oidc.utils.PkceUtils;
import org.keycloak.protocol.saml.JaxrsSAML2BindingBuilder;
import org.keycloak.protocol.saml.SamlClient;
import org.keycloak.protocol.saml.SamlProtocol;
import org.keycloak.rar.AuthorizationRequestContext;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.dpop.DPoP;
import org.keycloak.representations.idm.authorization.AuthorizationRequest.Metadata;
import org.keycloak.saml.common.constants.JBossSAMLConstants;
import org.keycloak.saml.common.constants.JBossSAMLURIConstants;
import org.keycloak.saml.common.exceptions.ConfigurationException;
@ -92,6 +65,7 @@ import org.keycloak.services.managers.AuthenticationSessionManager;
import org.keycloak.services.managers.ClientManager;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.managers.UserSessionManager;
import org.keycloak.services.resources.Cors;
import org.keycloak.services.util.AuthorizationContextUtil;
import org.keycloak.services.util.DefaultClientSessionContext;
import org.keycloak.services.util.DPoPUtil;
@ -104,7 +78,6 @@ import org.w3c.dom.Document;
import org.w3c.dom.Element;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.InternalServerErrorException;
import jakarta.ws.rs.OPTIONS;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
@ -117,12 +90,7 @@ import jakarta.ws.rs.core.Response.Status;
import javax.xml.namespace.QName;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
@ -136,10 +104,6 @@ public class TokenEndpoint {
private OIDCAdvancedConfigWrapper clientConfig;
private DPoP dPoP;
private enum Action {
AUTHORIZATION_CODE, REFRESH_TOKEN, PASSWORD, CLIENT_CREDENTIALS, TOKEN_EXCHANGE, PERMISSION, OAUTH2_DEVICE_CODE, CIBA
}
private final KeycloakSession session;
private final HttpRequest request;
@ -154,7 +118,7 @@ public class TokenEndpoint {
private final RealmModel realm;
private final EventBuilder event;
private Action action;
private OAuth2GrantType grant;
private String grantType;
@ -195,31 +159,16 @@ public class TokenEndpoint {
checkRealm();
checkGrantType();
if (!action.equals(Action.PERMISSION)) {
if (!grant.getGrantType().equals(OAuth2Constants.UMA_GRANT_TYPE)) {
checkClient();
checkParameterDuplicated();
}
switch (action) {
case AUTHORIZATION_CODE:
return codeToToken();
case REFRESH_TOKEN:
return refreshTokenGrant();
case PASSWORD:
return resourceOwnerPasswordCredentialsGrant();
case CLIENT_CREDENTIALS:
return clientCredentialsGrant();
case TOKEN_EXCHANGE:
return tokenExchange();
case PERMISSION:
return permissionGrant();
case OAUTH2_DEVICE_CODE:
return oauth2DeviceCodeToToken();
case CIBA:
return cibaGrant();
}
OAuth2GrantType.Context context = new OAuth2GrantType.Context(session, realm,
client, clientConfig, clientConnection, clientAuthAttributes,
request, httpResponse, headers, formParams, event, cors, tokenManager, dPoP);
throw new RuntimeException("Unknown action " + action);
return grant.process(context);
}
@Path("introspect")
@ -267,34 +216,12 @@ public class TokenEndpoint {
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "Missing form parameter: " + OIDCLoginProtocol.GRANT_TYPE_PARAM, Response.Status.BAD_REQUEST);
}
if (grantType.equals(OAuth2Constants.AUTHORIZATION_CODE)) {
event.event(EventType.CODE_TO_TOKEN);
action = Action.AUTHORIZATION_CODE;
} else if (grantType.equals(OAuth2Constants.REFRESH_TOKEN)) {
event.event(EventType.REFRESH_TOKEN);
action = Action.REFRESH_TOKEN;
} else if (grantType.equals(OAuth2Constants.PASSWORD)) {
event.event(EventType.LOGIN);
action = Action.PASSWORD;
} else if (grantType.equals(OAuth2Constants.CLIENT_CREDENTIALS)) {
event.event(EventType.CLIENT_LOGIN);
action = Action.CLIENT_CREDENTIALS;
} else if (grantType.equals(OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE)) {
event.event(EventType.TOKEN_EXCHANGE);
action = Action.TOKEN_EXCHANGE;
} else if (grantType.equals(OAuth2Constants.UMA_GRANT_TYPE)) {
event.event(EventType.PERMISSION_TOKEN);
action = Action.PERMISSION;
} else if (grantType.equals(OAuth2Constants.DEVICE_CODE_GRANT_TYPE)) {
if (!Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) {
throw newUnsupportedGrantTypeException();
}
event.event(EventType.OAUTH2_DEVICE_CODE_TO_TOKEN);
action = Action.OAUTH2_DEVICE_CODE;
} else if (grantType.equals(OAuth2Constants.CIBA_GRANT_TYPE)) {
event.event(EventType.AUTHREQID_TO_TOKEN);
action = Action.CIBA;
} else {
grant = OAuth2GrantManager.resolve(session, grantType).orElseThrow(() -> newUnsupportedGrantTypeException());
event.event(grant.getEventType());
if (grantType.equals(OAuth2Constants.DEVICE_CODE_GRANT_TYPE)
&& !Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) {
throw newUnsupportedGrantTypeException();
}
@ -315,720 +242,6 @@ public class TokenEndpoint {
}
}
private void checkAndRetrieveDPoPProof(boolean isDPoPSupported) {
if (!isDPoPSupported) return;
if (clientConfig.isUseDPoP() || request.getHttpHeaders().getHeaderString(DPoPUtil.DPOP_HTTP_HEADER) != null) {
try {
dPoP = new DPoPUtil.Validator(session).request(request).uriInfo(session.getContext().getUri()).validate();
session.setAttribute(DPoPUtil.DPOP_SESSION_ATTRIBUTE, dPoP);
} catch (VerificationException ex) {
event.error(Errors.INVALID_DPOP_PROOF);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_DPOP_PROOF, ex.getMessage(), Response.Status.BAD_REQUEST);
}
}
}
public Response codeToToken() {
checkAndRetrieveDPoPProof(Profile.isFeatureEnabled(Profile.Feature.DPOP));
String code = formParams.getFirst(OAuth2Constants.CODE);
if (code == null) {
event.error(Errors.INVALID_CODE);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "Missing parameter: " + OAuth2Constants.CODE, Response.Status.BAD_REQUEST);
}
OAuth2CodeParser.ParseResult parseResult = OAuth2CodeParser.parseCode(session, code, realm, event);
if (parseResult.isIllegalCode()) {
AuthenticatedClientSessionModel clientSession = parseResult.getClientSession();
// Attempt to use same code twice should invalidate existing clientSession
if (clientSession != null) {
clientSession.detachFromUserSession();
}
event.error(Errors.INVALID_CODE);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Code not valid", Response.Status.BAD_REQUEST);
}
AuthenticatedClientSessionModel clientSession = parseResult.getClientSession();
if (parseResult.isExpiredCode()) {
event.error(Errors.EXPIRED_CODE);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Code is expired", Response.Status.BAD_REQUEST);
}
UserSessionModel userSession = null;
if (clientSession != null) {
userSession = clientSession.getUserSession();
}
if (userSession == null) {
event.error(Errors.USER_SESSION_NOT_FOUND);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "User session not found", Response.Status.BAD_REQUEST);
}
UserModel user = userSession.getUser();
if (user == null) {
event.error(Errors.USER_NOT_FOUND);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "User not found", Response.Status.BAD_REQUEST);
}
event.user(userSession.getUser());
if (!user.isEnabled()) {
event.error(Errors.USER_DISABLED);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "User disabled", Response.Status.BAD_REQUEST);
}
OAuth2Code codeData = parseResult.getCodeData();
String redirectUri = codeData.getRedirectUriParam();
String redirectUriParam = formParams.getFirst(OAuth2Constants.REDIRECT_URI);
// KEYCLOAK-4478 Backwards compatibility with the adapters earlier than KC 3.4.2
if (redirectUriParam != null && redirectUriParam.contains("session_state=") && !redirectUri.contains("session_state=")) {
redirectUriParam = KeycloakUriBuilder.fromUri(redirectUriParam)
.replaceQueryParam(OAuth2Constants.SESSION_STATE, null)
.build().toString();
}
if (redirectUri != null && !redirectUri.equals(redirectUriParam)) {
event.error(Errors.INVALID_CODE);
logger.tracef("Parameter 'redirect_uri' did not match originally saved redirect URI used in initial OIDC request. Saved redirectUri: %s, redirectUri parameter: %s", redirectUri, redirectUriParam);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Incorrect redirect_uri", Response.Status.BAD_REQUEST);
}
if (!client.getClientId().equals(clientSession.getClient().getClientId())) {
event.error(Errors.INVALID_CODE);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Auth error", Response.Status.BAD_REQUEST);
}
if (!client.isStandardFlowEnabled()) {
event.error(Errors.NOT_ALLOWED);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Client not allowed to exchange code", Response.Status.BAD_REQUEST);
}
if (!AuthenticationManager.isSessionValid(realm, userSession)) {
event.error(Errors.USER_SESSION_NOT_FOUND);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Session not active", Response.Status.BAD_REQUEST);
}
// https://tools.ietf.org/html/rfc7636#section-4.6
String codeVerifier = formParams.getFirst(OAuth2Constants.CODE_VERIFIER);
String codeChallenge = codeData.getCodeChallenge();
String codeChallengeMethod = codeData.getCodeChallengeMethod();
String authUserId = user.getId();
String authUsername = user.getUsername();
if (authUserId == null) {
authUserId = "unknown";
}
if (authUsername == null) {
authUsername = "unknown";
}
if (codeChallengeMethod != null && !codeChallengeMethod.isEmpty()) {
PkceUtils.checkParamsForPkceEnforcedClient(codeVerifier, codeChallenge, codeChallengeMethod, authUserId, authUsername, event, cors);
} else {
// PKCE Activation is OFF, execute the codes implemented in KEYCLOAK-2604
PkceUtils.checkParamsForPkceNotEnforcedClient(codeVerifier, codeChallenge, codeChallengeMethod, authUserId, authUsername, event, cors);
}
try {
session.clientPolicy().triggerOnEvent(new TokenRequestContext(formParams, parseResult));
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
}
updateClientSession(clientSession);
updateUserSessionFromClientAuth(userSession);
// Compute client scopes again from scope parameter. Check if user still has them granted
// (but in code-to-token request, it could just theoretically happen that they are not available)
String scopeParam = codeData.getScope();
Supplier<Stream<ClientScopeModel>> clientScopesSupplier = () -> TokenManager.getRequestedClientScopes(scopeParam, client);
if (!TokenManager.verifyConsentStillAvailable(session, user, client, clientScopesSupplier.get())) {
event.error(Errors.NOT_ALLOWED);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_SCOPE, "Client no longer has requested consent from user", Response.Status.BAD_REQUEST);
}
ClientSessionContext clientSessionCtx = DefaultClientSessionContext.fromClientSessionAndScopeParameter(clientSession, scopeParam, session);
// Set nonce as an attribute in the ClientSessionContext. Will be used for the token generation
clientSessionCtx.setAttribute(OIDCLoginProtocol.NONCE_PARAM, codeData.getNonce());
return createTokenResponse(user, userSession, clientSessionCtx, scopeParam, true, s -> {return new TokenResponseContext(formParams, parseResult, clientSessionCtx, s);});
}
public Response createTokenResponse(UserModel user, UserSessionModel userSession, ClientSessionContext clientSessionCtx,
String scopeParam, boolean code, Function<TokenManager.AccessTokenResponseBuilder, ClientPolicyContext> clientPolicyContextGenerator) {
AccessToken token = tokenManager.createClientAccessToken(session, realm, client, user, userSession, clientSessionCtx);
TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager
.responseBuilder(realm, client, event, session, userSession, clientSessionCtx).accessToken(token);
boolean useRefreshToken = clientConfig.isUseRefreshToken();
if (useRefreshToken) {
responseBuilder.generateRefreshToken();
}
checkAndBindMtlsHoKToken(responseBuilder, useRefreshToken);
checkAndBindDPoPToken(responseBuilder, useRefreshToken && client.isPublicClient(), Profile.isFeatureEnabled(Profile.Feature.DPOP));
if (TokenUtil.isOIDCRequest(scopeParam)) {
responseBuilder.generateIDToken().generateAccessTokenHash();
}
if (clientPolicyContextGenerator != null) {
try {
session.clientPolicy().triggerOnEvent(clientPolicyContextGenerator.apply(responseBuilder));
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
}
}
AccessTokenResponse res = null;
if (code) {
try {
res = responseBuilder.build();
} catch (RuntimeException re) {
if ("can not get encryption KEK".equals(re.getMessage())) {
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST,
"can not get encryption KEK", Response.Status.BAD_REQUEST);
} else {
throw re;
}
}
} else {
res = responseBuilder.build();
}
event.success();
return cors.builder(Response.ok(res).type(MediaType.APPLICATION_JSON_TYPE)).build();
}
private void checkAndBindMtlsHoKToken(TokenManager.AccessTokenResponseBuilder responseBuilder, boolean useRefreshToken) {
// KEYCLOAK-6771 Certificate Bound Token
// https://tools.ietf.org/html/draft-ietf-oauth-mtls-08#section-3
if (clientConfig.isUseMtlsHokToken()) {
AccessToken.Confirmation confirmation = MtlsHoKTokenUtil.bindTokenWithClientCertificate(request, session);
if (confirmation != null) {
responseBuilder.getAccessToken().setConfirmation(confirmation);
if (useRefreshToken) {
responseBuilder.getRefreshToken().setConfirmation(confirmation);
}
} else {
event.error(Errors.INVALID_REQUEST);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST,
"Client Certification missing for MTLS HoK Token Binding", Response.Status.BAD_REQUEST);
}
}
}
private void checkAndBindDPoPToken(TokenManager.AccessTokenResponseBuilder responseBuilder, boolean useRefreshToken, boolean isDPoPSupported) {
if (!isDPoPSupported) return;
if (clientConfig.isUseDPoP() || dPoP != null) {
DPoPUtil.bindToken(responseBuilder.getAccessToken(), dPoP);
responseBuilder.getAccessToken().type(DPoPUtil.DPOP_TOKEN_TYPE);
responseBuilder.responseTokenType(DPoPUtil.DPOP_TOKEN_TYPE);
// Bind refresh tokens for public clients, See "Section 5. DPoP Access Token Request" from DPoP specification
if (useRefreshToken) {
DPoPUtil.bindToken(responseBuilder.getRefreshToken(), dPoP);
}
}
}
public Response refreshTokenGrant() {
checkAndRetrieveDPoPProof(Profile.isFeatureEnabled(Profile.Feature.DPOP));
String refreshToken = formParams.getFirst(OAuth2Constants.REFRESH_TOKEN);
if (refreshToken == null) {
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "No refresh token", Response.Status.BAD_REQUEST);
}
String scopeParameter = getRequestedScopes();
try {
session.clientPolicy().triggerOnEvent(new TokenRefreshContext(formParams));
refreshToken = formParams.getFirst(OAuth2Constants.REFRESH_TOKEN);
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
}
AccessTokenResponse res;
try {
// KEYCLOAK-6771 Certificate Bound Token
TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.refreshAccessToken(session, session.getContext().getUri(), clientConnection, realm, client, refreshToken, event, headers, request, scopeParameter);
checkAndBindMtlsHoKToken(responseBuilder, clientConfig.isUseRefreshToken());
checkAndBindDPoPToken(responseBuilder, clientConfig.isUseRefreshToken() && (client.isPublicClient() || client.isBearerOnly()), Profile.isFeatureEnabled(Profile.Feature.DPOP));
session.clientPolicy().triggerOnEvent(new TokenRefreshResponseContext(formParams, responseBuilder));
res = responseBuilder.build();
if (!responseBuilder.isOfflineToken()) {
UserSessionModel userSession = session.sessions().getUserSession(realm, res.getSessionState());
AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(client.getId());
updateClientSession(clientSession);
updateUserSessionFromClientAuth(userSession);
}
} catch (OAuthErrorException e) {
logger.trace(e.getMessage(), e);
// KEYCLOAK-6771 Certificate Bound Token
if (MtlsHoKTokenUtil.CERT_VERIFY_ERROR_DESC.equals(e.getDescription())) {
event.error(Errors.NOT_ALLOWED);
throw new CorsErrorResponseException(cors, e.getError(), e.getDescription(), Response.Status.UNAUTHORIZED);
} else {
event.error(Errors.INVALID_TOKEN);
throw new CorsErrorResponseException(cors, e.getError(), e.getDescription(), Response.Status.BAD_REQUEST);
}
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
}
event.success();
return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
private void updateClientSession(AuthenticatedClientSessionModel clientSession) {
if(clientSession == null) {
ServicesLogger.LOGGER.clientSessionNull();
return;
}
String adapterSessionId = formParams.getFirst(AdapterConstants.CLIENT_SESSION_STATE);
if (adapterSessionId != null) {
String adapterSessionHost = formParams.getFirst(AdapterConstants.CLIENT_SESSION_HOST);
logger.debugf("Adapter Session '%s' saved in ClientSession for client '%s'. Host is '%s'", adapterSessionId, client.getClientId(), adapterSessionHost);
String oldClientSessionState = clientSession.getNote(AdapterConstants.CLIENT_SESSION_STATE);
if (!adapterSessionId.equals(oldClientSessionState)) {
clientSession.setNote(AdapterConstants.CLIENT_SESSION_STATE, adapterSessionId);
}
String oldClientSessionHost = clientSession.getNote(AdapterConstants.CLIENT_SESSION_HOST);
if (!Objects.equals(adapterSessionHost, oldClientSessionHost)) {
clientSession.setNote(AdapterConstants.CLIENT_SESSION_HOST, adapterSessionHost);
}
}
}
private void updateUserSessionFromClientAuth(UserSessionModel userSession) {
for (Map.Entry<String, String> attr : clientAuthAttributes.entrySet()) {
userSession.setNote(attr.getKey(), attr.getValue());
}
}
public Response resourceOwnerPasswordCredentialsGrant() {
event.detail(Details.AUTH_METHOD, "oauth_credentials");
if (!client.isDirectAccessGrantsEnabled()) {
event.error(Errors.NOT_ALLOWED);
throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Client not allowed for direct access grants", Response.Status.BAD_REQUEST);
}
if (client.isConsentRequired()) {
event.error(Errors.CONSENT_DENIED);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_CLIENT, "Client requires user consent", Response.Status.BAD_REQUEST);
}
try {
session.clientPolicy().triggerOnEvent(new ResourceOwnerPasswordCredentialsContext(formParams));
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
}
String scope = getRequestedScopes();
RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, false);
AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(client);
authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
authSession.setAction(AuthenticatedClientSessionModel.Action.AUTHENTICATE.name());
authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));
authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scope);
AuthenticationFlowModel flow = AuthenticationFlowResolver.resolveDirectGrantFlow(authSession);
String flowId = flow.getId();
AuthenticationProcessor processor = new AuthenticationProcessor();
processor.setAuthenticationSession(authSession)
.setFlowId(flowId)
.setFlowPath("token")
.setConnection(clientConnection)
.setEventBuilder(event)
.setRealm(realm)
.setSession(session)
.setUriInfo(session.getContext().getUri())
.setRequest(request);
Response challenge = processor.authenticateOnly();
if (challenge != null) {
// Remove authentication session as "Resource Owner Password Credentials Grant" is single-request scoped authentication
new AuthenticationSessionManager(session).removeAuthenticationSession(realm, authSession, false);
cors.build(httpResponse);
return challenge;
}
processor.evaluateRequiredActionTriggers();
UserModel user = authSession.getAuthenticatedUser();
if (user.getRequiredActionsStream().count() > 0 || authSession.getRequiredActions().size() > 0) {
// Remove authentication session as "Resource Owner Password Credentials Grant" is single-request scoped authentication
new AuthenticationSessionManager(session).removeAuthenticationSession(realm, authSession, false);
event.error(Errors.RESOLVE_REQUIRED_ACTIONS);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Account is not fully set up", Response.Status.BAD_REQUEST);
}
AuthenticationManager.setClientScopesInSession(authSession);
ClientSessionContext clientSessionCtx = processor.attachSession();
UserSessionModel userSession = processor.getUserSession();
updateUserSessionFromClientAuth(userSession);
TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager
.responseBuilder(realm, client, event, session, userSession, clientSessionCtx).generateAccessToken();
boolean useRefreshToken = clientConfig.isUseRefreshToken();
if (useRefreshToken) {
responseBuilder.generateRefreshToken();
}
String scopeParam = clientSessionCtx.getClientSession().getNote(OAuth2Constants.SCOPE);
if (TokenUtil.isOIDCRequest(scopeParam)) {
responseBuilder.generateIDToken().generateAccessTokenHash();
}
checkAndBindMtlsHoKToken(responseBuilder, useRefreshToken);
try {
session.clientPolicy().triggerOnEvent(new ResourceOwnerPasswordCredentialsResponseContext(formParams, clientSessionCtx, responseBuilder));
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
}
AccessTokenResponse res = responseBuilder.build();
event.success();
AuthenticationManager.logSuccess(session, authSession);
return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
public Response clientCredentialsGrant() {
if (client.isBearerOnly()) {
event.error(Errors.INVALID_CLIENT);
throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Bearer-only client not allowed to retrieve service account", Response.Status.UNAUTHORIZED);
}
if (client.isPublicClient()) {
event.error(Errors.INVALID_CLIENT);
throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Public client not allowed to retrieve service account", Response.Status.UNAUTHORIZED);
}
if (!client.isServiceAccountsEnabled()) {
event.error(Errors.INVALID_CLIENT);
throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Client not enabled to retrieve service account", Response.Status.UNAUTHORIZED);
}
UserModel clientUser = session.users().getServiceAccount(client);
if (clientUser == null || client.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, ServiceAccountConstants.CLIENT_ID_PROTOCOL_MAPPER) == null) {
// May need to handle bootstrap here as well
logger.debugf("Service account user for client '%s' not found or default protocol mapper for service account not found. Creating now", client.getClientId());
new ClientManager(new RealmManager(session)).enableServiceAccount(client);
clientUser = session.users().getServiceAccount(client);
}
String clientUsername = clientUser.getUsername();
event.detail(Details.USERNAME, clientUsername);
event.user(clientUser);
if (!clientUser.isEnabled()) {
event.error(Errors.USER_DISABLED);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "User '" + clientUsername + "' disabled", Response.Status.UNAUTHORIZED);
}
String scope = getRequestedScopes();
RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, false);
AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(client);
authSession.setAuthenticatedUser(clientUser);
authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));
authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scope);
// persisting of userSession by default
UserSessionModel.SessionPersistenceState sessionPersistenceState = UserSessionModel.SessionPersistenceState.PERSISTENT;
boolean useRefreshToken = clientConfig.isUseRefreshTokenForClientCredentialsGrant();
if (!useRefreshToken) {
// we don't want to store a session hence we mark it as transient, see KEYCLOAK-9551
sessionPersistenceState = UserSessionModel.SessionPersistenceState.TRANSIENT;
}
UserSessionModel userSession = new UserSessionManager(session).createUserSession(authSession.getParentSession().getId(), realm, clientUser, clientUsername,
clientConnection.getRemoteAddr(), ServiceAccountConstants.CLIENT_AUTH, false, null, null, sessionPersistenceState);
event.session(userSession);
AuthenticationManager.setClientScopesInSession(authSession);
ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(session, userSession, authSession);
// Notes about client details
userSession.setNote(ServiceAccountConstants.CLIENT_ID_SESSION_NOTE, client.getClientId()); // This is for backwards compatibility
userSession.setNote(ServiceAccountConstants.CLIENT_ID, client.getClientId());
userSession.setNote(ServiceAccountConstants.CLIENT_HOST, clientConnection.getRemoteHost());
userSession.setNote(ServiceAccountConstants.CLIENT_ADDRESS, clientConnection.getRemoteAddr());
try {
session.clientPolicy().triggerOnEvent(new ServiceAccountTokenRequestContext(formParams, clientSessionCtx.getClientSession()));
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
}
updateUserSessionFromClientAuth(userSession);
TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, event, session, userSession, clientSessionCtx)
.generateAccessToken();
// Make refresh token generation optional, see KEYCLOAK-9551
if (useRefreshToken) {
responseBuilder = responseBuilder.generateRefreshToken();
} else {
responseBuilder.getAccessToken().setSessionState(null);
}
checkAndBindMtlsHoKToken(responseBuilder, useRefreshToken);
String scopeParam = clientSessionCtx.getClientSession().getNote(OAuth2Constants.SCOPE);
if (TokenUtil.isOIDCRequest(scopeParam)) {
responseBuilder.generateIDToken().generateAccessTokenHash();
}
try {
session.clientPolicy().triggerOnEvent(new ServiceAccountTokenResponseContext(formParams, clientSessionCtx.getClientSession(), responseBuilder));
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
}
// TODO : do the same as codeToToken()
AccessTokenResponse res = null;
try {
res = responseBuilder.build();
} catch (RuntimeException re) {
if ("can not get encryption KEK".equals(re.getMessage())) {
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST,
"can not get encryption KEK", Response.Status.BAD_REQUEST);
} else {
throw re;
}
}
event.success();
return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
private String getRequestedScopes() {
String scope = formParams.getFirst(OAuth2Constants.SCOPE);
boolean validScopes;
if (Profile.isFeatureEnabled(Profile.Feature.DYNAMIC_SCOPES)) {
AuthorizationRequestContext authorizationRequestContext = AuthorizationContextUtil.getAuthorizationRequestContextFromScopes(session, scope);
validScopes = TokenManager.isValidScope(scope, authorizationRequestContext, client);
} else {
validScopes = TokenManager.isValidScope(scope, client);
}
if (!validScopes) {
event.error(Errors.INVALID_REQUEST);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_SCOPE, "Invalid scopes: " + scope,
Status.BAD_REQUEST);
}
return scope;
}
public Response tokenExchange() {
ProfileHelper.requireFeature(Profile.Feature.TOKEN_EXCHANGE);
event.detail(Details.AUTH_METHOD, "token_exchange");
event.client(client);
TokenExchangeContext context = new TokenExchangeContext(
session,
formParams,
cors,
realm,
event,
client,
clientConnection,
headers,
tokenManager,
clientAuthAttributes);
return session.getKeycloakSessionFactory()
.getProviderFactoriesStream(TokenExchangeProvider.class)
.sorted((f1, f2) -> f2.order() - f1.order())
.map(f -> session.getProvider(TokenExchangeProvider.class, f.getId()))
.filter(p -> p.supports(context))
.findFirst()
.orElseThrow(() -> new InternalServerErrorException("No token exchange provider available"))
.exchange(context);
}
public Response permissionGrant() {
event.detail(Details.AUTH_METHOD, "oauth_credentials");
String accessTokenString = null;
String authorizationHeader = headers.getRequestHeaders().getFirst(HttpHeaders.AUTHORIZATION);
if (authorizationHeader != null && authorizationHeader.toLowerCase().startsWith("bearer")) {
accessTokenString = new AppAuthManager().extractAuthorizationHeaderToken(headers);
}
// we allow public clients to authenticate using a bearer token, where the token should be a valid access token.
// public clients don't have secret and should be able to obtain a RPT by providing an access token previously issued by the server
if (accessTokenString != null) {
AccessToken accessToken = Tokens.getAccessToken(session);
if (accessToken == null) {
try {
// In case the access token is invalid because it's expired or the user is disabled, identify the client
// from the access token anyway in order to set correct CORS headers.
AccessToken invalidToken = new JWSInput(accessTokenString).readJsonContent(AccessToken.class);
ClientModel client = realm.getClientByClientId(invalidToken.getIssuedFor());
cors.allowedOrigins(session, client);
event.client(client);
} catch (JWSInputException ignore) {
}
event.error(Errors.INVALID_TOKEN);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Invalid bearer token", Status.UNAUTHORIZED);
}
ClientModel client = realm.getClientByClientId(accessToken.getIssuedFor());
session.getContext().setClient(client);
cors.allowedOrigins(session, client);
event.client(client);
}
String claimToken = null;
// claim_token is optional, if provided we just grab it from the request
if (formParams.containsKey("claim_token")) {
claimToken = formParams.get("claim_token").get(0);
}
String claimTokenFormat = formParams.getFirst("claim_token_format");
if (claimToken != null && claimTokenFormat == null) {
claimTokenFormat = AuthorizationTokenService.CLAIM_TOKEN_FORMAT_ID_TOKEN;
}
String subjectToken = formParams.getFirst("subject_token");
if (accessTokenString == null) {
// in case no bearer token is provided, we force client authentication
checkClient();
// if a claim token is provided, we check if the format is a OpenID Connect IDToken and assume the token represents the identity asking for permissions
if (AuthorizationTokenService.CLAIM_TOKEN_FORMAT_ID_TOKEN.equalsIgnoreCase(claimTokenFormat)) {
accessTokenString = claimToken;
} else if (subjectToken != null) {
accessTokenString = subjectToken;
} else {
// Clients need to authenticate in order to obtain a RPT from the server.
// In order to support cases where the client is obtaining permissions on its on behalf, we issue a temporary access token
accessTokenString = AccessTokenResponse.class.cast(clientCredentialsGrant().getEntity()).getToken();
}
}
AuthorizationTokenService.KeycloakAuthorizationRequest authorizationRequest = new AuthorizationTokenService.KeycloakAuthorizationRequest(session.getProvider(AuthorizationProvider.class),
tokenManager, event, this.request, cors, clientConnection);
authorizationRequest.setTicket(formParams.getFirst("ticket"));
authorizationRequest.setClaimToken(claimToken);
authorizationRequest.setClaimTokenFormat(claimTokenFormat);
authorizationRequest.setPct(formParams.getFirst("pct"));
String rpt = formParams.getFirst("rpt");
if (rpt != null) {
AccessToken accessToken = session.tokens().decode(rpt, AccessToken.class);
if (accessToken == null) {
event.error(Errors.INVALID_REQUEST);
throw new CorsErrorResponseException(cors, "invalid_rpt", "RPT signature is invalid", Status.FORBIDDEN);
}
authorizationRequest.setRpt(accessToken);
}
authorizationRequest.setScope(formParams.getFirst("scope"));
String audienceParam = formParams.getFirst("audience");
authorizationRequest.setAudience(audienceParam);
authorizationRequest.setSubjectToken(accessTokenString);
event.detail(Details.AUDIENCE, audienceParam);
String submitRequest = formParams.getFirst("submit_request");
authorizationRequest.setSubmitRequest(submitRequest == null ? true : Boolean.valueOf(submitRequest));
// permissions have a format like RESOURCE#SCOPE1,SCOPE2
List<String> permissions = formParams.get("permission");
if (permissions != null) {
event.detail(Details.PERMISSION, String.join("|", permissions));
String permissionResourceFormat = formParams.getFirst("permission_resource_format");
boolean permissionResourceMatchingUri = Boolean.parseBoolean(formParams.getFirst("permission_resource_matching_uri"));
authorizationRequest.addPermissions(permissions, permissionResourceFormat, permissionResourceMatchingUri);
}
Metadata metadata = new Metadata();
String responseIncludeResourceName = formParams.getFirst("response_include_resource_name");
if (responseIncludeResourceName != null) {
metadata.setIncludeResourceName(Boolean.parseBoolean(responseIncludeResourceName));
}
String responsePermissionsLimit = formParams.getFirst("response_permissions_limit");
if (responsePermissionsLimit != null) {
metadata.setLimit(Integer.parseInt(responsePermissionsLimit));
}
metadata.setResponseMode(formParams.getFirst("response_mode"));
authorizationRequest.setMetadata(metadata);
Response authorizationResponse = AuthorizationTokenService.instance().authorize(authorizationRequest);
event.success();
return authorizationResponse;
}
public Response oauth2DeviceCodeToToken() {
DeviceGrantType deviceGrantType = new DeviceGrantType(formParams, client, session, this, realm, event, cors);
return deviceGrantType.oauth2DeviceFlow();
}
public Response cibaGrant() {
CibaGrantType grantType = new CibaGrantType(formParams, client, session, this, realm, event, cors);
return grantType.cibaGrant();
}
public static class TokenExchangeSamlProtocol extends SamlProtocol {
final SamlClient samlClient;

View file

@ -0,0 +1,218 @@
/*
* Copyright 2024 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.oidc.grants;
import jakarta.ws.rs.core.Response;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.jboss.logging.Logger;
import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException;
import org.keycloak.common.Profile;
import org.keycloak.common.util.KeycloakUriBuilder;
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;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.protocol.oidc.utils.OAuth2Code;
import org.keycloak.protocol.oidc.utils.OAuth2CodeParser;
import org.keycloak.protocol.oidc.utils.PkceUtils;
import org.keycloak.services.CorsErrorResponseException;
import org.keycloak.services.clientpolicy.ClientPolicyException;
import org.keycloak.services.clientpolicy.context.TokenRequestContext;
import org.keycloak.services.clientpolicy.context.TokenResponseContext;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.util.DefaultClientSessionContext;
/**
* OAuth 2.0 Authorization Code Grant
* https://datatracker.ietf.org/doc/html/rfc6749#section-4.1
*
* @author <a href="mailto:demetrio@carretti.pro">Dmitry Telegin</a> (et al.)
*/
public class AuthorizationCodeGrantType extends OAuth2GrantTypeBase {
private static final Logger logger = Logger.getLogger(AuthorizationCodeGrantType.class);
private static final String PROVIDER_ID = "authorization_code";
@Override
public Response process(Context context) {
initialize(context);
checkAndRetrieveDPoPProof(Profile.isFeatureEnabled(Profile.Feature.DPOP));
String code = formParams.getFirst(OAuth2Constants.CODE);
if (code == null) {
event.error(Errors.INVALID_CODE);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "Missing parameter: " + OAuth2Constants.CODE, Response.Status.BAD_REQUEST);
}
OAuth2CodeParser.ParseResult parseResult = OAuth2CodeParser.parseCode(session, code, realm, event);
if (parseResult.isIllegalCode()) {
AuthenticatedClientSessionModel clientSession = parseResult.getClientSession();
// Attempt to use same code twice should invalidate existing clientSession
if (clientSession != null) {
clientSession.detachFromUserSession();
}
event.error(Errors.INVALID_CODE);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Code not valid", Response.Status.BAD_REQUEST);
}
AuthenticatedClientSessionModel clientSession = parseResult.getClientSession();
if (parseResult.isExpiredCode()) {
event.error(Errors.EXPIRED_CODE);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Code is expired", Response.Status.BAD_REQUEST);
}
UserSessionModel userSession = null;
if (clientSession != null) {
userSession = clientSession.getUserSession();
}
if (userSession == null) {
event.error(Errors.USER_SESSION_NOT_FOUND);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "User session not found", Response.Status.BAD_REQUEST);
}
UserModel user = userSession.getUser();
if (user == null) {
event.error(Errors.USER_NOT_FOUND);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "User not found", Response.Status.BAD_REQUEST);
}
event.user(userSession.getUser());
if (!user.isEnabled()) {
event.error(Errors.USER_DISABLED);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "User disabled", Response.Status.BAD_REQUEST);
}
OAuth2Code codeData = parseResult.getCodeData();
String redirectUri = codeData.getRedirectUriParam();
String redirectUriParam = formParams.getFirst(OAuth2Constants.REDIRECT_URI);
// KEYCLOAK-4478 Backwards compatibility with the adapters earlier than KC 3.4.2
if (redirectUriParam != null && redirectUriParam.contains("session_state=") && !redirectUri.contains("session_state=")) {
redirectUriParam = KeycloakUriBuilder.fromUri(redirectUriParam)
.replaceQueryParam(OAuth2Constants.SESSION_STATE, null)
.build().toString();
}
if (redirectUri != null && !redirectUri.equals(redirectUriParam)) {
event.error(Errors.INVALID_CODE);
logger.tracef("Parameter 'redirect_uri' did not match originally saved redirect URI used in initial OIDC request. Saved redirectUri: %s, redirectUri parameter: %s", redirectUri, redirectUriParam);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Incorrect redirect_uri", Response.Status.BAD_REQUEST);
}
if (!client.getClientId().equals(clientSession.getClient().getClientId())) {
event.error(Errors.INVALID_CODE);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Auth error", Response.Status.BAD_REQUEST);
}
if (!client.isStandardFlowEnabled()) {
event.error(Errors.NOT_ALLOWED);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Client not allowed to exchange code", Response.Status.BAD_REQUEST);
}
if (!AuthenticationManager.isSessionValid(realm, userSession)) {
event.error(Errors.USER_SESSION_NOT_FOUND);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Session not active", Response.Status.BAD_REQUEST);
}
// https://tools.ietf.org/html/rfc7636#section-4.6
String codeVerifier = formParams.getFirst(OAuth2Constants.CODE_VERIFIER);
String codeChallenge = codeData.getCodeChallenge();
String codeChallengeMethod = codeData.getCodeChallengeMethod();
String authUserId = user.getId();
String authUsername = user.getUsername();
if (authUserId == null) {
authUserId = "unknown";
}
if (authUsername == null) {
authUsername = "unknown";
}
if (codeChallengeMethod != null && !codeChallengeMethod.isEmpty()) {
PkceUtils.checkParamsForPkceEnforcedClient(codeVerifier, codeChallenge, codeChallengeMethod, authUserId, authUsername, event, cors);
} else {
// PKCE Activation is OFF, execute the codes implemented in KEYCLOAK-2604
PkceUtils.checkParamsForPkceNotEnforcedClient(codeVerifier, codeChallenge, codeChallengeMethod, authUserId, authUsername, event, cors);
}
try {
session.clientPolicy().triggerOnEvent(new TokenRequestContext(formParams, parseResult));
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
}
updateClientSession(clientSession);
updateUserSessionFromClientAuth(userSession);
// Compute client scopes again from scope parameter. Check if user still has them granted
// (but in code-to-token request, it could just theoretically happen that they are not available)
String scopeParam = codeData.getScope();
Supplier<Stream<ClientScopeModel>> clientScopesSupplier = () -> TokenManager.getRequestedClientScopes(scopeParam, client);
if (!TokenManager.verifyConsentStillAvailable(session, user, client, clientScopesSupplier.get())) {
event.error(Errors.NOT_ALLOWED);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_SCOPE, "Client no longer has requested consent from user", Response.Status.BAD_REQUEST);
}
ClientSessionContext clientSessionCtx = DefaultClientSessionContext.fromClientSessionAndScopeParameter(clientSession, scopeParam, session);
// Set nonce as an attribute in the ClientSessionContext. Will be used for the token generation
clientSessionCtx.setAttribute(OIDCLoginProtocol.NONCE_PARAM, codeData.getNonce());
return createTokenResponse(user, userSession, clientSessionCtx, scopeParam, true, s -> {return new TokenResponseContext(formParams, parseResult, clientSessionCtx, s);});
}
@Override
public OAuth2GrantType create(KeycloakSession session) {
return new AuthorizationCodeGrantType();
}
@Override
public String getId() {
return PROVIDER_ID;
}
@Override
public String getGrantType() {
return OAuth2Constants.AUTHORIZATION_CODE;
}
@Override
public EventType getEventType() {
return EventType.CODE_TO_TOKEN;
}
}

View file

@ -0,0 +1,200 @@
/*
* Copyright 2024 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.oidc.grants;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException;
import org.keycloak.common.constants.ServiceAccountConstants;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventType;
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;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.services.CorsErrorResponseException;
import org.keycloak.services.Urls;
import org.keycloak.services.clientpolicy.ClientPolicyException;
import org.keycloak.services.clientpolicy.context.ServiceAccountTokenRequestContext;
import org.keycloak.services.clientpolicy.context.ServiceAccountTokenResponseContext;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.managers.AuthenticationSessionManager;
import org.keycloak.services.managers.ClientManager;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.managers.UserSessionManager;
import org.keycloak.sessions.AuthenticationSessionModel;
import org.keycloak.sessions.RootAuthenticationSessionModel;
import org.keycloak.util.TokenUtil;
/**
* OAuth 2.0 Client Credentials Grant
* https://datatracker.ietf.org/doc/html/rfc6749#section-4.4
*
* @author <a href="mailto:demetrio@carretti.pro">Dmitry Telegin</a> (et al.)
*/
public class ClientCredentialsGrantType extends OAuth2GrantTypeBase {
private static final String PROVIDER_ID = "client_credentials";
private static final Logger logger = Logger.getLogger(ClientCredentialsGrantType.class);
@Override
public Response process(Context context) {
initialize(context);
if (client.isBearerOnly()) {
event.error(Errors.INVALID_CLIENT);
throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Bearer-only client not allowed to retrieve service account", Response.Status.UNAUTHORIZED);
}
if (client.isPublicClient()) {
event.error(Errors.INVALID_CLIENT);
throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Public client not allowed to retrieve service account", Response.Status.UNAUTHORIZED);
}
if (!client.isServiceAccountsEnabled()) {
event.error(Errors.INVALID_CLIENT);
throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Client not enabled to retrieve service account", Response.Status.UNAUTHORIZED);
}
UserModel clientUser = session.users().getServiceAccount(client);
if (clientUser == null || client.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, ServiceAccountConstants.CLIENT_ID_PROTOCOL_MAPPER) == null) {
// May need to handle bootstrap here as well
logger.debugf("Service account user for client '%s' not found or default protocol mapper for service account not found. Creating now", client.getClientId());
new ClientManager(new RealmManager(session)).enableServiceAccount(client);
clientUser = session.users().getServiceAccount(client);
}
String clientUsername = clientUser.getUsername();
event.detail(Details.USERNAME, clientUsername);
event.user(clientUser);
if (!clientUser.isEnabled()) {
event.error(Errors.USER_DISABLED);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "User '" + clientUsername + "' disabled", Response.Status.UNAUTHORIZED);
}
String scope = getRequestedScopes();
RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, false);
AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(client);
authSession.setAuthenticatedUser(clientUser);
authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));
authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scope);
// persisting of userSession by default
UserSessionModel.SessionPersistenceState sessionPersistenceState = UserSessionModel.SessionPersistenceState.PERSISTENT;
boolean useRefreshToken = clientConfig.isUseRefreshTokenForClientCredentialsGrant();
if (!useRefreshToken) {
// we don't want to store a session hence we mark it as transient, see KEYCLOAK-9551
sessionPersistenceState = UserSessionModel.SessionPersistenceState.TRANSIENT;
}
UserSessionModel userSession = new UserSessionManager(session).createUserSession(authSession.getParentSession().getId(), realm, clientUser, clientUsername,
clientConnection.getRemoteAddr(), ServiceAccountConstants.CLIENT_AUTH, false, null, null, sessionPersistenceState);
event.session(userSession);
AuthenticationManager.setClientScopesInSession(authSession);
ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(session, userSession, authSession);
// Notes about client details
userSession.setNote(ServiceAccountConstants.CLIENT_ID_SESSION_NOTE, client.getClientId()); // This is for backwards compatibility
userSession.setNote(ServiceAccountConstants.CLIENT_ID, client.getClientId());
userSession.setNote(ServiceAccountConstants.CLIENT_HOST, clientConnection.getRemoteHost());
userSession.setNote(ServiceAccountConstants.CLIENT_ADDRESS, clientConnection.getRemoteAddr());
try {
session.clientPolicy().triggerOnEvent(new ServiceAccountTokenRequestContext(formParams, clientSessionCtx.getClientSession()));
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
}
updateUserSessionFromClientAuth(userSession);
TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, event, session, userSession, clientSessionCtx)
.generateAccessToken();
// Make refresh token generation optional, see KEYCLOAK-9551
if (useRefreshToken) {
responseBuilder = responseBuilder.generateRefreshToken();
} else {
responseBuilder.getAccessToken().setSessionState(null);
}
checkAndBindMtlsHoKToken(responseBuilder, useRefreshToken);
String scopeParam = clientSessionCtx.getClientSession().getNote(OAuth2Constants.SCOPE);
if (TokenUtil.isOIDCRequest(scopeParam)) {
responseBuilder.generateIDToken().generateAccessTokenHash();
}
try {
session.clientPolicy().triggerOnEvent(new ServiceAccountTokenResponseContext(formParams, clientSessionCtx.getClientSession(), responseBuilder));
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
}
// TODO : do the same as codeToToken()
AccessTokenResponse res = null;
try {
res = responseBuilder.build();
} catch (RuntimeException re) {
if ("can not get encryption KEK".equals(re.getMessage())) {
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST,
"can not get encryption KEK", Response.Status.BAD_REQUEST);
} else {
throw re;
}
}
event.success();
return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
@Override
public OAuth2GrantType create(KeycloakSession session) {
return new ClientCredentialsGrantType();
}
@Override
public String getId() {
return PROVIDER_ID;
}
@Override
public String getGrantType() {
return OAuth2Constants.CLIENT_CREDENTIALS;
}
@Override
public EventType getEventType() {
return EventType.CLIENT_LOGIN;
}
}

View file

@ -0,0 +1,43 @@
/*
* Copyright 2024 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.oidc.grants;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.keycloak.models.KeycloakSession;
/**
* A class to register and resolve OAuth 2.0 Grant Type implementations according to provider priorities
*
* @author <a href="mailto:demetrio@carretti.pro">Dmitry Telegin</a>
*/
public class OAuth2GrantManager {
private static final Map<String, OAuth2GrantType> MAP = new HashMap<>();
public static void register(OAuth2GrantType grant) {
MAP.merge(grant.getGrantType(), grant, (g1, g2) -> g1.order() > g2.order() ? g1 : g2);
}
public static Optional<OAuth2GrantType> resolve(KeycloakSession session, String grantType) {
return Optional.ofNullable(MAP.get(grantType)).map(g -> g.create(session));
}
}

View file

@ -0,0 +1,278 @@
/*
* Copyright 2024 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.oidc.grants;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import org.jboss.logging.Logger;
import org.keycloak.Config;
import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException;
import org.keycloak.common.ClientConnection;
import org.keycloak.common.Profile;
import org.keycloak.common.VerificationException;
import org.keycloak.constants.AdapterConstants;
import org.keycloak.events.Errors;
import org.keycloak.events.EventBuilder;
import org.keycloak.http.HttpRequest;
import org.keycloak.http.HttpResponse;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientSessionContext;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.protocol.oidc.utils.AuthorizeClientUtil;
import org.keycloak.rar.AuthorizationRequestContext;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.dpop.DPoP;
import org.keycloak.services.CorsErrorResponseException;
import org.keycloak.services.ServicesLogger;
import org.keycloak.services.clientpolicy.ClientPolicyContext;
import org.keycloak.services.clientpolicy.ClientPolicyException;
import org.keycloak.services.resources.Cors;
import org.keycloak.services.util.AuthorizationContextUtil;
import org.keycloak.services.util.DPoPUtil;
import org.keycloak.services.util.MtlsHoKTokenUtil;
import org.keycloak.util.TokenUtil;
/**
* Base class for OAuth 2.0 grant types
*
* @author <a href="mailto:demetrio@carretti.pro">Dmitry Telegin</a> (et al.)
*/
public abstract class OAuth2GrantTypeBase implements OAuth2GrantType {
private static final Logger logger = Logger.getLogger(OAuth2GrantTypeBase.class);
protected KeycloakSession session;
protected RealmModel realm;
protected ClientModel client;
protected OIDCAdvancedConfigWrapper clientConfig;
protected ClientConnection clientConnection;
protected Map<String, String> clientAuthAttributes;
protected MultivaluedMap<String, String> formParams;
protected EventBuilder event;
protected Cors cors;
protected TokenManager tokenManager;
protected DPoP dPoP;
protected HttpRequest request;
protected HttpResponse response;
protected HttpHeaders headers;
protected void initialize(Context context) {
this.session = context.session;
this.realm = context.realm;
this.client = context.client;
this.clientConfig = (OIDCAdvancedConfigWrapper) context.clientConfig;
this.clientConnection = context.clientConnection;
this.clientAuthAttributes = context.clientAuthAttributes;
this.request = context.request;
this.response = context.response;
this.headers = context.headers;
this.formParams = context.formParams;
this.event = context.event;
this.cors = (Cors) context.cors;
this.tokenManager = (TokenManager) context.tokenManager;
this.dPoP = context.dPoP;
}
protected Response createTokenResponse(UserModel user, UserSessionModel userSession, ClientSessionContext clientSessionCtx,
String scopeParam, boolean code, Function<TokenManager.AccessTokenResponseBuilder, ClientPolicyContext> clientPolicyContextGenerator) {
AccessToken token = tokenManager.createClientAccessToken(session, realm, client, user, userSession, clientSessionCtx);
TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager
.responseBuilder(realm, client, event, session, userSession, clientSessionCtx).accessToken(token);
boolean useRefreshToken = clientConfig.isUseRefreshToken();
if (useRefreshToken) {
responseBuilder.generateRefreshToken();
}
checkAndBindMtlsHoKToken(responseBuilder, useRefreshToken);
checkAndBindDPoPToken(responseBuilder, useRefreshToken && client.isPublicClient(), Profile.isFeatureEnabled(Profile.Feature.DPOP));
if (TokenUtil.isOIDCRequest(scopeParam)) {
responseBuilder.generateIDToken().generateAccessTokenHash();
}
if (clientPolicyContextGenerator != null) {
try {
session.clientPolicy().triggerOnEvent(clientPolicyContextGenerator.apply(responseBuilder));
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
}
}
AccessTokenResponse res = null;
if (code) {
try {
res = responseBuilder.build();
} catch (RuntimeException re) {
if ("can not get encryption KEK".equals(re.getMessage())) {
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST,
"can not get encryption KEK", Response.Status.BAD_REQUEST);
} else {
throw re;
}
}
} else {
res = responseBuilder.build();
}
event.success();
return cors.builder(Response.ok(res).type(MediaType.APPLICATION_JSON_TYPE)).build();
}
protected void checkAndBindMtlsHoKToken(TokenManager.AccessTokenResponseBuilder responseBuilder, boolean useRefreshToken) {
// KEYCLOAK-6771 Certificate Bound Token
// https://tools.ietf.org/html/draft-ietf-oauth-mtls-08#section-3
if (clientConfig.isUseMtlsHokToken()) {
AccessToken.Confirmation confirmation = MtlsHoKTokenUtil.bindTokenWithClientCertificate(request, session);
if (confirmation != null) {
responseBuilder.getAccessToken().setConfirmation(confirmation);
if (useRefreshToken) {
responseBuilder.getRefreshToken().setConfirmation(confirmation);
}
} else {
event.error(Errors.INVALID_REQUEST);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST,
"Client Certification missing for MTLS HoK Token Binding", Response.Status.BAD_REQUEST);
}
}
}
protected void checkAndBindDPoPToken(TokenManager.AccessTokenResponseBuilder responseBuilder, boolean useRefreshToken, boolean isDPoPSupported) {
if (!isDPoPSupported) return;
if (clientConfig.isUseDPoP() || dPoP != null) {
DPoPUtil.bindToken(responseBuilder.getAccessToken(), dPoP);
responseBuilder.getAccessToken().type(DPoPUtil.DPOP_TOKEN_TYPE);
responseBuilder.responseTokenType(DPoPUtil.DPOP_TOKEN_TYPE);
// Bind refresh tokens for public clients, See "Section 5. DPoP Access Token Request" from DPoP specification
if (useRefreshToken) {
DPoPUtil.bindToken(responseBuilder.getRefreshToken(), dPoP);
}
}
}
protected void updateClientSession(AuthenticatedClientSessionModel clientSession) {
if(clientSession == null) {
ServicesLogger.LOGGER.clientSessionNull();
return;
}
String adapterSessionId = formParams.getFirst(AdapterConstants.CLIENT_SESSION_STATE);
if (adapterSessionId != null) {
String adapterSessionHost = formParams.getFirst(AdapterConstants.CLIENT_SESSION_HOST);
logger.debugf("Adapter Session '%s' saved in ClientSession for client '%s'. Host is '%s'", adapterSessionId, client.getClientId(), adapterSessionHost);
String oldClientSessionState = clientSession.getNote(AdapterConstants.CLIENT_SESSION_STATE);
if (!adapterSessionId.equals(oldClientSessionState)) {
clientSession.setNote(AdapterConstants.CLIENT_SESSION_STATE, adapterSessionId);
}
String oldClientSessionHost = clientSession.getNote(AdapterConstants.CLIENT_SESSION_HOST);
if (!Objects.equals(adapterSessionHost, oldClientSessionHost)) {
clientSession.setNote(AdapterConstants.CLIENT_SESSION_HOST, adapterSessionHost);
}
}
}
protected void updateUserSessionFromClientAuth(UserSessionModel userSession) {
for (Map.Entry<String, String> attr : clientAuthAttributes.entrySet()) {
userSession.setNote(attr.getKey(), attr.getValue());
}
}
protected void checkAndRetrieveDPoPProof(boolean isDPoPSupported) {
if (!isDPoPSupported) return;
if (clientConfig.isUseDPoP() || request.getHttpHeaders().getHeaderString(DPoPUtil.DPOP_HTTP_HEADER) != null) {
try {
dPoP = new DPoPUtil.Validator(session).request(request).uriInfo(session.getContext().getUri()).validate();
session.setAttribute(DPoPUtil.DPOP_SESSION_ATTRIBUTE, dPoP);
} catch (VerificationException ex) {
event.error(Errors.INVALID_DPOP_PROOF);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_DPOP_PROOF, ex.getMessage(), Response.Status.BAD_REQUEST);
}
}
}
protected String getRequestedScopes() {
String scope = formParams.getFirst(OAuth2Constants.SCOPE);
boolean validScopes;
if (Profile.isFeatureEnabled(Profile.Feature.DYNAMIC_SCOPES)) {
AuthorizationRequestContext authorizationRequestContext = AuthorizationContextUtil.getAuthorizationRequestContextFromScopes(session, scope);
validScopes = TokenManager.isValidScope(scope, authorizationRequestContext, client);
} else {
validScopes = TokenManager.isValidScope(scope, client);
}
if (!validScopes) {
event.error(Errors.INVALID_REQUEST);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_SCOPE, "Invalid scopes: " + scope,
Response.Status.BAD_REQUEST);
}
return scope;
}
protected void checkClient() {
AuthorizeClientUtil.ClientAuthResult clientAuth = AuthorizeClientUtil.authorizeClient(session, event, cors);
client = clientAuth.getClient();
clientAuthAttributes = clientAuth.getClientAuthAttributes();
clientConfig = OIDCAdvancedConfigWrapper.fromClientModel(client);
cors.allowedOrigins(session, client);
if (client.isBearerOnly()) {
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_CLIENT, "Bearer-only not allowed", Response.Status.BAD_REQUEST);
}
}
@Override
public void close() {
}
@Override
public void postInit(KeycloakSessionFactory factory) {
OAuth2GrantManager.register(this);
}
@Override
public void init(Config.Scope config) {
}
}

View file

@ -0,0 +1,212 @@
/*
* Copyright 2024 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.oidc.grants;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
import java.util.List;
import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException;
import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.authorization.AuthorizationTokenService;
import org.keycloak.authorization.util.Tokens;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventType;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.JWSInputException;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.idm.authorization.AuthorizationRequest;
import org.keycloak.services.CorsErrorResponseException;
import org.keycloak.services.managers.AppAuthManager;
/**
* User-Managed Access (UMA) 2.0 Grant for OAuth 2.0 Authorization
* https://docs.kantarainitiative.org/uma/wg/rec-oauth-uma-grant-2.0.html#uma-grant-type
*
* @author <a href="mailto:demetrio@carretti.pro">Dmitry Telegin</a> (et al.)
*/
public class PermissionGrantType extends OAuth2GrantTypeBase {
private static final String PROVIDER_ID = "uma_ticket";
@Override
public Response process(Context context) {
initialize(context);
event.detail(Details.AUTH_METHOD, "oauth_credentials");
String accessTokenString = null;
String authorizationHeader = headers.getRequestHeaders().getFirst(HttpHeaders.AUTHORIZATION);
if (authorizationHeader != null && authorizationHeader.toLowerCase().startsWith("bearer")) {
accessTokenString = new AppAuthManager().extractAuthorizationHeaderToken(headers);
}
// we allow public clients to authenticate using a bearer token, where the token should be a valid access token.
// public clients don't have secret and should be able to obtain a RPT by providing an access token previously issued by the server
if (accessTokenString != null) {
AccessToken accessToken = Tokens.getAccessToken(session);
if (accessToken == null) {
try {
// In case the access token is invalid because it's expired or the user is disabled, identify the client
// from the access token anyway in order to set correct CORS headers.
AccessToken invalidToken = new JWSInput(accessTokenString).readJsonContent(AccessToken.class);
ClientModel client = realm.getClientByClientId(invalidToken.getIssuedFor());
cors.allowedOrigins(session, client);
event.client(client);
} catch (JWSInputException ignore) {
}
event.error(Errors.INVALID_TOKEN);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Invalid bearer token", Response.Status.UNAUTHORIZED);
}
ClientModel client = realm.getClientByClientId(accessToken.getIssuedFor());
session.getContext().setClient(client);
cors.allowedOrigins(session, client);
event.client(client);
}
String claimToken = null;
// claim_token is optional, if provided we just grab it from the request
if (formParams.containsKey("claim_token")) {
claimToken = formParams.get("claim_token").get(0);
}
String claimTokenFormat = formParams.getFirst("claim_token_format");
if (claimToken != null && claimTokenFormat == null) {
claimTokenFormat = AuthorizationTokenService.CLAIM_TOKEN_FORMAT_ID_TOKEN;
}
String subjectToken = formParams.getFirst("subject_token");
if (accessTokenString == null) {
// in case no bearer token is provided, we force client authentication
checkClient();
// if a claim token is provided, we check if the format is a OpenID Connect IDToken and assume the token represents the identity asking for permissions
if (AuthorizationTokenService.CLAIM_TOKEN_FORMAT_ID_TOKEN.equalsIgnoreCase(claimTokenFormat)) {
accessTokenString = claimToken;
} else if (subjectToken != null) {
accessTokenString = subjectToken;
} else {
// Clients need to authenticate in order to obtain a RPT from the server.
// In order to support cases where the client is obtaining permissions on its on behalf, we issue a temporary access token
OAuth2GrantType clientCredentialsGrant = OAuth2GrantManager.resolve(session, OAuth2Constants.CLIENT_CREDENTIALS).get();
Context clientCredentialsContext = new Context(session, realm, client, clientConfig, clientConnection, clientAuthAttributes, request, response, headers, formParams, event, cors, tokenManager, dPoP);
accessTokenString = AccessTokenResponse.class.cast(clientCredentialsGrant.process(clientCredentialsContext).getEntity()).getToken();
}
}
AuthorizationTokenService.KeycloakAuthorizationRequest authorizationRequest = new AuthorizationTokenService.KeycloakAuthorizationRequest(session.getProvider(AuthorizationProvider.class),
tokenManager, event, this.request, cors, clientConnection);
authorizationRequest.setTicket(formParams.getFirst("ticket"));
authorizationRequest.setClaimToken(claimToken);
authorizationRequest.setClaimTokenFormat(claimTokenFormat);
authorizationRequest.setPct(formParams.getFirst("pct"));
String rpt = formParams.getFirst("rpt");
if (rpt != null) {
AccessToken accessToken = session.tokens().decode(rpt, AccessToken.class);
if (accessToken == null) {
event.error(Errors.INVALID_REQUEST);
throw new CorsErrorResponseException(cors, "invalid_rpt", "RPT signature is invalid", Response.Status.FORBIDDEN);
}
authorizationRequest.setRpt(accessToken);
}
authorizationRequest.setScope(formParams.getFirst("scope"));
String audienceParam = formParams.getFirst("audience");
authorizationRequest.setAudience(audienceParam);
authorizationRequest.setSubjectToken(accessTokenString);
event.detail(Details.AUDIENCE, audienceParam);
String submitRequest = formParams.getFirst("submit_request");
authorizationRequest.setSubmitRequest(submitRequest == null ? true : Boolean.valueOf(submitRequest));
// permissions have a format like RESOURCE#SCOPE1,SCOPE2
List<String> permissions = formParams.get("permission");
if (permissions != null) {
event.detail(Details.PERMISSION, String.join("|", permissions));
String permissionResourceFormat = formParams.getFirst("permission_resource_format");
boolean permissionResourceMatchingUri = Boolean.parseBoolean(formParams.getFirst("permission_resource_matching_uri"));
authorizationRequest.addPermissions(permissions, permissionResourceFormat, permissionResourceMatchingUri);
}
AuthorizationRequest.Metadata metadata = new AuthorizationRequest.Metadata();
String responseIncludeResourceName = formParams.getFirst("response_include_resource_name");
if (responseIncludeResourceName != null) {
metadata.setIncludeResourceName(Boolean.parseBoolean(responseIncludeResourceName));
}
String responsePermissionsLimit = formParams.getFirst("response_permissions_limit");
if (responsePermissionsLimit != null) {
metadata.setLimit(Integer.parseInt(responsePermissionsLimit));
}
metadata.setResponseMode(formParams.getFirst("response_mode"));
authorizationRequest.setMetadata(metadata);
Response authorizationResponse = AuthorizationTokenService.instance().authorize(authorizationRequest);
event.success();
return authorizationResponse;
}
@Override
public String getGrantType() {
return OAuth2Constants.UMA_GRANT_TYPE;
}
@Override
public EventType getEventType() {
return EventType.PERMISSION_TOKEN;
}
@Override
public OAuth2GrantType create(KeycloakSession session) {
return new PermissionGrantType();
}
@Override
public String getId() {
return PROVIDER_ID;
}
}

View file

@ -0,0 +1,131 @@
/*
* Copyright 2024 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.oidc.grants;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException;
import org.keycloak.common.Profile;
import org.keycloak.events.Errors;
import org.keycloak.events.EventType;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.UserSessionModel;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.services.CorsErrorResponseException;
import org.keycloak.services.clientpolicy.ClientPolicyException;
import org.keycloak.services.clientpolicy.context.TokenRefreshContext;
import org.keycloak.services.clientpolicy.context.TokenRefreshResponseContext;
import org.keycloak.services.util.MtlsHoKTokenUtil;
/**
* OAuth 2.0 Refresh Token Grant
* https://datatracker.ietf.org/doc/html/rfc6749#section-6
*
* @author <a href="mailto:demetrio@carretti.pro">Dmitry Telegin</a> (et al.)
*/
public class RefreshTokenGrantType extends OAuth2GrantTypeBase {
private static final String PROVIDER_ID = "refresh_token";
private static final Logger logger = Logger.getLogger(RefreshTokenGrantType.class);
@Override
public Response process(Context context) {
initialize(context);
checkAndRetrieveDPoPProof(Profile.isFeatureEnabled(Profile.Feature.DPOP));
String refreshToken = formParams.getFirst(OAuth2Constants.REFRESH_TOKEN);
if (refreshToken == null) {
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "No refresh token", Response.Status.BAD_REQUEST);
}
String scopeParameter = getRequestedScopes();
try {
session.clientPolicy().triggerOnEvent(new TokenRefreshContext(formParams));
refreshToken = formParams.getFirst(OAuth2Constants.REFRESH_TOKEN);
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
}
AccessTokenResponse res;
try {
// KEYCLOAK-6771 Certificate Bound Token
TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.refreshAccessToken(session, session.getContext().getUri(), clientConnection, realm, client, refreshToken, event, headers, request, scopeParameter);
checkAndBindMtlsHoKToken(responseBuilder, clientConfig.isUseRefreshToken());
checkAndBindDPoPToken(responseBuilder, clientConfig.isUseRefreshToken() && (client.isPublicClient() || client.isBearerOnly()), Profile.isFeatureEnabled(Profile.Feature.DPOP));
session.clientPolicy().triggerOnEvent(new TokenRefreshResponseContext(formParams, responseBuilder));
res = responseBuilder.build();
if (!responseBuilder.isOfflineToken()) {
UserSessionModel userSession = session.sessions().getUserSession(realm, res.getSessionState());
AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(client.getId());
updateClientSession(clientSession);
updateUserSessionFromClientAuth(userSession);
}
} catch (OAuthErrorException e) {
logger.trace(e.getMessage(), e);
// KEYCLOAK-6771 Certificate Bound Token
if (MtlsHoKTokenUtil.CERT_VERIFY_ERROR_DESC.equals(e.getDescription())) {
event.error(Errors.NOT_ALLOWED);
throw new CorsErrorResponseException(cors, e.getError(), e.getDescription(), Response.Status.UNAUTHORIZED);
} else {
event.error(Errors.INVALID_TOKEN);
throw new CorsErrorResponseException(cors, e.getError(), e.getDescription(), Response.Status.BAD_REQUEST);
}
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
}
event.success();
return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
@Override
public String getGrantType() {
return OAuth2Constants.REFRESH_TOKEN;
}
@Override
public EventType getEventType() {
return EventType.REFRESH_TOKEN;
}
@Override
public OAuth2GrantType create(KeycloakSession session) {
return new RefreshTokenGrantType();
}
@Override
public String getId() {
return PROVIDER_ID;
}
}

View file

@ -0,0 +1,179 @@
/*
* Copyright 2024 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.oidc.grants;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException;
import org.keycloak.authentication.AuthenticationProcessor;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventType;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.AuthenticationFlowModel;
import org.keycloak.models.ClientSessionContext;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.utils.AuthenticationFlowResolver;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.services.CorsErrorResponseException;
import org.keycloak.services.Urls;
import org.keycloak.services.clientpolicy.ClientPolicyException;
import org.keycloak.services.clientpolicy.context.ResourceOwnerPasswordCredentialsContext;
import org.keycloak.services.clientpolicy.context.ResourceOwnerPasswordCredentialsResponseContext;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.managers.AuthenticationSessionManager;
import org.keycloak.sessions.AuthenticationSessionModel;
import org.keycloak.sessions.RootAuthenticationSessionModel;
import org.keycloak.util.TokenUtil;
/**
* OAuth 2.0 Resource Owner Password Credentials Grant
* https://datatracker.ietf.org/doc/html/rfc6749#section-4.3
*
* @author <a href="mailto:demetrio@carretti.pro">Dmitry Telegin</a> (et al.)
*/
public class ResourceOwnerPasswordCredentialsGrantType extends OAuth2GrantTypeBase {
private static final String PROVIDER_ID = "password";
private static final Logger logger = Logger.getLogger(ResourceOwnerPasswordCredentialsGrantType.class);
@Override
public Response process(Context context) {
initialize(context);
event.detail(Details.AUTH_METHOD, "oauth_credentials");
if (!client.isDirectAccessGrantsEnabled()) {
event.error(Errors.NOT_ALLOWED);
throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Client not allowed for direct access grants", Response.Status.BAD_REQUEST);
}
if (client.isConsentRequired()) {
event.error(Errors.CONSENT_DENIED);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_CLIENT, "Client requires user consent", Response.Status.BAD_REQUEST);
}
try {
session.clientPolicy().triggerOnEvent(new ResourceOwnerPasswordCredentialsContext(formParams));
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
}
String scope = getRequestedScopes();
RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, false);
AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(client);
authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
authSession.setAction(AuthenticatedClientSessionModel.Action.AUTHENTICATE.name());
authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));
authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scope);
AuthenticationFlowModel flow = AuthenticationFlowResolver.resolveDirectGrantFlow(authSession);
String flowId = flow.getId();
AuthenticationProcessor processor = new AuthenticationProcessor();
processor.setAuthenticationSession(authSession)
.setFlowId(flowId)
.setConnection(clientConnection)
.setEventBuilder(event)
.setRealm(realm)
.setSession(session)
.setUriInfo(session.getContext().getUri())
.setRequest(request);
Response challenge = processor.authenticateOnly();
if (challenge != null) {
// Remove authentication session as "Resource Owner Password Credentials Grant" is single-request scoped authentication
new AuthenticationSessionManager(session).removeAuthenticationSession(realm, authSession, false);
cors.build(response);
return challenge;
}
processor.evaluateRequiredActionTriggers();
UserModel user = authSession.getAuthenticatedUser();
if (user.getRequiredActionsStream().count() > 0 || authSession.getRequiredActions().size() > 0) {
// Remove authentication session as "Resource Owner Password Credentials Grant" is single-request scoped authentication
new AuthenticationSessionManager(session).removeAuthenticationSession(realm, authSession, false);
event.error(Errors.RESOLVE_REQUIRED_ACTIONS);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Account is not fully set up", Response.Status.BAD_REQUEST);
}
AuthenticationManager.setClientScopesInSession(authSession);
ClientSessionContext clientSessionCtx = processor.attachSession();
UserSessionModel userSession = processor.getUserSession();
updateUserSessionFromClientAuth(userSession);
TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager
.responseBuilder(realm, client, event, session, userSession, clientSessionCtx).generateAccessToken();
boolean useRefreshToken = clientConfig.isUseRefreshToken();
if (useRefreshToken) {
responseBuilder.generateRefreshToken();
}
String scopeParam = clientSessionCtx.getClientSession().getNote(OAuth2Constants.SCOPE);
if (TokenUtil.isOIDCRequest(scopeParam)) {
responseBuilder.generateIDToken().generateAccessTokenHash();
}
checkAndBindMtlsHoKToken(responseBuilder, useRefreshToken);
try {
session.clientPolicy().triggerOnEvent(new ResourceOwnerPasswordCredentialsResponseContext(formParams, clientSessionCtx, responseBuilder));
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
}
AccessTokenResponse res = responseBuilder.build();
event.success();
AuthenticationManager.logSuccess(session, authSession);
return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
@Override
public String getGrantType() {
return OAuth2Constants.PASSWORD;
}
@Override
public EventType getEventType() {
return EventType.LOGIN;
}
@Override
public OAuth2GrantType create(KeycloakSession session) {
return new ResourceOwnerPasswordCredentialsGrantType();
}
@Override
public String getId() {
return PROVIDER_ID;
}
}

View file

@ -0,0 +1,92 @@
/*
* Copyright 2024 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.oidc.grants;
import jakarta.ws.rs.InternalServerErrorException;
import jakarta.ws.rs.core.Response;
import org.keycloak.OAuth2Constants;
import org.keycloak.common.Profile;
import org.keycloak.events.Details;
import org.keycloak.events.EventType;
import org.keycloak.models.KeycloakSession;
import org.keycloak.protocol.oidc.TokenExchangeContext;
import org.keycloak.protocol.oidc.TokenExchangeProvider;
import org.keycloak.utils.ProfileHelper;
/**
* OAuth 2.0 Authorization Code Grant
* https://datatracker.ietf.org/doc/html/rfc8693#section-2.1
*
* @author <a href="mailto:demetrio@carretti.pro">Dmitry Telegin</a> (et al.)
*/
public class TokenExchangeGrantType extends OAuth2GrantTypeBase {
private static final String PROVIDER_ID = "token_exchange";
@Override
public Response process(Context context) {
initialize(context);
ProfileHelper.requireFeature(Profile.Feature.TOKEN_EXCHANGE);
event.detail(Details.AUTH_METHOD, "token_exchange");
event.client(client);
TokenExchangeContext exchange = new TokenExchangeContext(
session,
formParams,
cors,
realm,
event,
client,
clientConnection,
headers,
tokenManager,
clientAuthAttributes);
return session.getKeycloakSessionFactory()
.getProviderFactoriesStream(TokenExchangeProvider.class)
.sorted((f1, f2) -> f2.order() - f1.order())
.map(f -> session.getProvider(TokenExchangeProvider.class, f.getId()))
.filter(p -> p.supports(exchange))
.findFirst()
.orElseThrow(() -> new InternalServerErrorException("No token exchange provider available"))
.exchange(exchange);
}
@Override
public String getGrantType() {
return OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE;
}
@Override
public EventType getEventType() {
return EventType.TOKEN_EXCHANGE;
}
@Override
public OAuth2GrantType create(KeycloakSession session) {
return new TokenExchangeGrantType();
}
@Override
public String getId() {
return PROVIDER_ID;
}
}

View file

@ -18,37 +18,35 @@
package org.keycloak.protocol.oidc.grants.ciba;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import org.jboss.logging.Logger;
import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException;
import org.keycloak.authentication.AuthenticationProcessor;
import org.keycloak.common.Profile;
import org.keycloak.common.util.Time;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventBuilder;
import org.keycloak.events.EventType;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientScopeModel;
import org.keycloak.models.ClientSessionContext;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.OAuth2DeviceCodeModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserConsentModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.protocol.oidc.grants.OAuth2GrantTypeBase;
import org.keycloak.protocol.oidc.grants.ciba.channel.CIBAAuthenticationRequest;
import org.keycloak.protocol.oidc.grants.ciba.clientpolicy.context.BackchannelTokenRequestContext;
import org.keycloak.protocol.oidc.grants.ciba.clientpolicy.context.BackchannelTokenResponseContext;
import org.keycloak.protocol.oidc.grants.ciba.endpoints.CibaRootEndpoint;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.protocol.oidc.endpoints.TokenEndpoint;
import org.keycloak.protocol.oidc.grants.device.DeviceGrantType;
import org.keycloak.services.CorsErrorResponseException;
import org.keycloak.services.ErrorResponseException;
@ -63,12 +61,17 @@ import org.keycloak.sessions.RootAuthenticationSessionModel;
import org.keycloak.utils.ProfileHelper;
import java.util.Map;
import org.keycloak.protocol.oidc.grants.OAuth2GrantType;
/**
* OpenID Connect Client-Initiated Backchannel Authentication Flow
* https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.10.1
*
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/
public class CibaGrantType {
public class CibaGrantType extends OAuth2GrantTypeBase {
private static final String PROVIDER_ID = "ciba";
private static final Logger logger = Logger.getLogger(CibaGrantType.class);
public static final String IS_CONSENT_REQUIRED = "is_consent_required";
@ -107,26 +110,10 @@ public class CibaGrantType {
return uriBuilder.path(OIDCLoginProtocolService.class, "resolveExtension").resolveTemplate("extension", CibaRootEndpoint.PROVIDER_ID, false).path(CibaRootEndpoint.class, "authenticate");
}
private final MultivaluedMap<String, String> formParams;
private final ClientModel client;
private final KeycloakSession session;
private final TokenEndpoint tokenEndpoint;
private final RealmModel realm;
private final EventBuilder event;
private final Cors cors;
@Override
public Response process(Context context) {
initialize(context);
public CibaGrantType(MultivaluedMap<String, String> formParams, ClientModel client, KeycloakSession session,
TokenEndpoint tokenEndpoint, RealmModel realm, EventBuilder event, Cors cors) {
this.formParams = formParams;
this.client = client;
this.session = session;
this.tokenEndpoint = tokenEndpoint;
this.realm = realm;
this.event = event;
this.cors = cors;
}
public Response cibaGrant() {
ProfileHelper.requireFeature(Profile.Feature.CIBA);
if (!realm.getCibaPolicy().isOIDCCIBAGrantEnabled(client)) {
@ -212,7 +199,7 @@ public class CibaGrantType {
int authTime = Time.currentTime();
userSession.setNote(AuthenticationManager.AUTH_TIME, String.valueOf(authTime));
return tokenEndpoint.createTokenResponse(user, userSession, clientSessionCtx, scopeParam, true,s -> {return new BackchannelTokenResponseContext(request, formParams, clientSessionCtx, s);});
return createTokenResponse(user, userSession, clientSessionCtx, scopeParam, true,s -> {return new BackchannelTokenResponseContext(request, formParams, clientSessionCtx, s);});
}
@ -307,4 +294,25 @@ public class CibaGrantType {
private static void logDebug(String message, CIBAAuthenticationRequest request) {
logger.debugf("CIBA Grant :: authentication channel %s clientId = %s, authResultId = %s", message, request.getIssuedFor(), request.getAuthResultId());
}
@Override
public String getGrantType() {
return OAuth2Constants.CIBA_GRANT_TYPE;
}
@Override
public EventType getEventType() {
return EventType.AUTHREQID_TO_TOKEN;
}
@Override
public OAuth2GrantType create(KeycloakSession session) {
return new CibaGrantType();
}
@Override
public String getId() {
return PROVIDER_ID;
}
}

View file

@ -24,6 +24,7 @@ import org.keycloak.OAuthErrorException;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventBuilder;
import org.keycloak.events.EventType;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientSessionContext;
@ -41,7 +42,7 @@ import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.protocol.oidc.endpoints.AuthorizationEndpoint;
import org.keycloak.protocol.oidc.endpoints.TokenEndpoint;
import org.keycloak.protocol.oidc.grants.OAuth2GrantTypeBase;
import org.keycloak.protocol.oidc.grants.device.clientpolicy.context.DeviceTokenRequestContext;
import org.keycloak.protocol.oidc.grants.device.clientpolicy.context.DeviceTokenResponseContext;
import org.keycloak.protocol.oidc.grants.device.endpoints.DeviceEndpoint;
@ -56,19 +57,24 @@ import org.keycloak.services.resources.RealmsResource;
import org.keycloak.services.util.DefaultClientSessionContext;
import org.keycloak.sessions.AuthenticationSessionModel;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import jakarta.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.Map;
import org.keycloak.protocol.oidc.grants.OAuth2GrantType;
/**
* OAuth 2.0 Device Authorization Grant
* https://datatracker.ietf.org/doc/html/rfc8628#section-3.4
*
* @author <a href="mailto:h2-wada@nri.co.jp">Hiroyuki Wada</a>
* @author <a href="mailto:michito.okai.zn@hitachi.com">Michito Okai</a>
*/
public class DeviceGrantType {
public class DeviceGrantType extends OAuth2GrantTypeBase {
private static final String PROVIDER_ID = "device_code";
// OAuth 2.0 Device Authorization Grant
public static final String OAUTH2_DEVICE_VERIFIED_USER_CODE = "OAUTH2_DEVICE_VERIFIED_USER_CODE";
@ -200,30 +206,10 @@ public class DeviceGrantType {
return false;
}
private MultivaluedMap<String, String> formParams;
private ClientModel client;
@Override
public Response process(Context context) {
initialize(context);
private KeycloakSession session;
private TokenEndpoint tokenEndpoint;
private final RealmModel realm;
private final EventBuilder event;
private Cors cors;
public DeviceGrantType(MultivaluedMap<String, String> formParams, ClientModel client, KeycloakSession session,
TokenEndpoint tokenEndpoint, RealmModel realm, EventBuilder event, Cors cors) {
this.formParams = formParams;
this.client = client;
this.session = session;
this.tokenEndpoint = tokenEndpoint;
this.realm = realm;
this.event = event;
this.cors = cors;
}
public Response oauth2DeviceFlow() {
if (!realm.getOAuth2DeviceConfig().isOAuth2DeviceAuthorizationGrantEnabled(client)) {
event.error(Errors.NOT_ALLOWED);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT,
@ -352,6 +338,27 @@ public class DeviceGrantType {
// Set nonce as an attribute in the ClientSessionContext. Will be used for the token generation
clientSessionCtx.setAttribute(OIDCLoginProtocol.NONCE_PARAM, deviceCodeModel.getNonce());
return tokenEndpoint.createTokenResponse(user, userSession, clientSessionCtx, scopeParam, false, s -> {return new DeviceTokenResponseContext(deviceCodeModel, formParams, clientSession, s);});
return createTokenResponse(user, userSession, clientSessionCtx, scopeParam, false, s -> {return new DeviceTokenResponseContext(deviceCodeModel, formParams, clientSession, s);});
}
@Override
public String getGrantType() {
return OAuth2Constants.DEVICE_CODE_GRANT_TYPE;
}
@Override
public EventType getEventType() {
return EventType.OAUTH2_DEVICE_CODE_TO_TOKEN;
}
@Override
public OAuth2GrantType create(KeycloakSession session) {
return new DeviceGrantType();
}
@Override
public String getId() {
return PROVIDER_ID;
}
}

View file

@ -0,0 +1,9 @@
org.keycloak.protocol.oidc.grants.AuthorizationCodeGrantType
org.keycloak.protocol.oidc.grants.ClientCredentialsGrantType
org.keycloak.protocol.oidc.grants.PermissionGrantType
org.keycloak.protocol.oidc.grants.RefreshTokenGrantType
org.keycloak.protocol.oidc.grants.ResourceOwnerPasswordCredentialsGrantType
org.keycloak.protocol.oidc.grants.TokenExchangeGrantType
org.keycloak.protocol.oidc.grants.ciba.CibaGrantType
org.keycloak.protocol.oidc.grants.device.DeviceGrantType