Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/guides/securing-apps/mcp-authz-server.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,19 @@ To configure the executor, create a client policy profile in the {project_name}
* *Trusted domains*: A list of domain patterns (wildcard) that the executor accepts for the Client ID URL and Client Metadata URL properties. For example, use `*.example.org` to accept any subdomain of `example.org`. If empty, all domains are denied.
* *Restrict same domain*: If `ON`, the executor verifies that the Client ID URL and Redirect URI in an authorization request, as well as URL-valued properties of the client metadata, are all under the same trusted domain.
* *Required properties*: A list of client metadata properties that must be present in the Client ID Metadata Document. If the fetched document does not include all the listed properties, the request is rejected.
* *Allowed grant types*: A list of grant types that a Client ID Metadata Document can enable for the client.
The executor excludes the grant types not included in this list from the `grant_types` property of the client metadata.
If the list is empty, only `authorization_code` and `refresh_token` are allowed.
If the client metadata omits the `grant_types` property, the executor treats it as `authorization_code` and `refresh_token`.
The executor also excludes the response types whose grant type is not allowed from the `response_types` property, for example `token` unless `implicit` is allowed.
If no response type is left, the executor rejects the client metadata.
The executor also disables the grant types no longer allowed for an existing client on every authorization request, even if the client metadata is not re-fetched or is not modified.
The executor also rejects a request obtaining a token by a grant type not allowed, for example a `client_credentials` grant request sent directly to the token endpoint, and disables the grant types no longer allowed for the client.
This includes issuing tokens by the implicit or hybrid flow when `implicit` is not allowed, even for a login that started while `implicit` was allowed, and a UMA permission request for a requesting party token when `urn:ietf:params:oauth:grant-type:uma-ticket` is not allowed, even if another client sends an access token of the client as a subject token.
For this purpose, the `client-id-uri` condition also applies to such a request of a client whose client ID matches the condition, so the other executors of the same client profile apply to it, too.
The `urn:ietf:params:oauth:grant-type:uma-ticket` grant type is allowed only if `client_credentials` is allowed too, because UMA authorization services give the client a service account.
Because a Client ID Metadata Document is fetched and registered without any authentication, be careful when adding other grant types.
For example, `client_credentials` gives the client a service account.
* *Only Allow Confidential Client*: If `ON`, the executor only accepts a Client ID Metadata Document representing a confidential client. In this case, the client metadata must include either a `jwks` or `jwks_uri` property and must use `private_key_jwt` or `tls_client_auth` as the token endpoint authentication method.
* *Accept Public Client with Confidential-only Grant Types*: If `ON`, the executor accepts a Client ID Metadata Document representing a public client even if it includes grant types that can be used only by a confidential client (e.g., `urn:ietf:params:oauth:grant-type:jwt-bearer`). The executor excludes such grant types from the client metadata. If `OFF`, the executor rejects such a Client ID Metadata Document.
* *Resource indicator allow list*: A list of values of the `resource` parameter that the executor accepts (e.g., `+https://example.com/mcp+`). This option is only effective if the `resource-indicators` feature is enabled. If the `resource` parameter value of an authorization request is not included in this list, the executor rejects the request. If the authorization request does not include the `resource` parameter, the executor does not enforce this list. If the list is empty, no `resource` parameter value is accepted. For an accepted `resource` parameter value, the executor adds to the client an `Audience` mapper whose `Included Custom Audience` field is the value so that the `aud` claim of an access token includes it.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public enum ClientPolicyEvent {
RESOURCE_OWNER_PASSWORD_CREDENTIALS_RESPONSE,
JWT_AUTHORIZATION_GRANT,
JWT_AUTHORIZATION_GRANT_RESPONSE,
PERMISSION_TOKEN_REQUEST,
IDENTITY_BROKERING_API,

SAML_AUTHN_REQUEST,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@
import org.keycloak.services.CorsErrorResponseException;
import org.keycloak.services.ErrorResponseException;
import org.keycloak.services.Urls;
import org.keycloak.services.clientpolicy.ClientPolicyException;
import org.keycloak.services.clientpolicy.context.PermissionTokenRequestContext;
import org.keycloak.services.cors.Cors;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.managers.AuthenticationSessionManager;
Expand Down Expand Up @@ -219,12 +221,15 @@ public Response authorize(KeycloakAuthorizationRequest request) {

request.setClaims(ticket.getClaims());

// the client sending the request, captured before validating the subject token as it changes the client in the session context
ClientModel requestingClient = request.getKeycloakSession().getContext().getClient();
EvaluationContext evaluationContext = createEvaluationContext(request);
KeycloakIdentity identity = KeycloakIdentity.class.cast(evaluationContext.getIdentity());

if (identity != null) {
event.user(identity.getId());
request.getKeycloakSession().getContext().setBearerToken(identity.getAccessToken());
checkClientPolicyForTokenClient(request, identity, requestingClient);
}

ResourceServer resourceServer = getResourceServer(ticket, request);
Expand Down Expand Up @@ -290,6 +295,38 @@ public Response authorize(KeycloakAuthorizationRequest request) {
}
}

// The RPT is issued for the client of the validated subject token (see createAuthorizationResponse), which can differ
// from the client sending the request, for example when a client sends a subject_token issued to another client.
// Client policies were applied only to the client sending the request, so they are also applied to the client of the token.
private void checkClientPolicyForTokenClient(KeycloakAuthorizationRequest request, KeycloakIdentity identity, ClientModel requestingClient) {
AccessToken accessToken = identity.getAccessToken();
if (accessToken == null || accessToken.getIssuedFor() == null) {
return;
}

KeycloakSession session = request.getKeycloakSession();
if (requestingClient != null && accessToken.getIssuedFor().equals(requestingClient.getClientId())) {
// client policies were already applied to this client
return;
}

ClientModel tokenClient = request.getRealm().getClientByClientId(accessToken.getIssuedFor());
if (tokenClient == null) {
return;
}

try {
session.clientPolicy().triggerOnEvent(new PermissionTokenRequestContext(session.getContext().getHttpRequest().getDecodedFormParameters(), tokenClient));
} catch (ClientPolicyException cpe) {
EventBuilder event = request.getEvent();
event.detail(Details.REASON, Details.CLIENT_POLICY_ERROR);
event.detail(Details.CLIENT_POLICY_ERROR, cpe.getError());
event.detail(Details.CLIENT_POLICY_ERROR_DETAIL, cpe.getErrorDetail());
event.error(cpe.getError());
throw new CorsErrorResponseException(request.getCors(), cpe.getError(), cpe.getErrorDetail(), Status.BAD_REQUEST);
}
}

private Response createSuccessfulResponse(Object response, KeycloakAuthorizationRequest request) {
return Cors.builder()
.checkAllowedOrigins(request.getKeycloakSession(), request.getKeycloakSession().getContext().getClient())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@
import java.util.Objects;

import org.keycloak.OAuth2Constants;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.representations.idm.ClientPolicyConditionConfigurationRepresentation;
import org.keycloak.services.clientpolicy.ClientPolicyContext;
import org.keycloak.services.clientpolicy.ClientPolicyException;
import org.keycloak.services.clientpolicy.ClientPolicyVote;
import org.keycloak.services.clientpolicy.condition.AbstractClientPolicyConditionProvider;
import org.keycloak.services.clientpolicy.context.AuthorizationRequestRedirectUriContext;
import org.keycloak.services.clientpolicy.context.ClientModelContext;
import org.keycloak.services.clientpolicy.context.PreAuthorizationRequestContext;

import com.fasterxml.jackson.annotation.JsonProperty;
Expand All @@ -24,6 +26,10 @@
* {@code AUTHORIZATION_REQUEST_REDIRECT_URI} events, it checks if the client ID is a URI and
* the scheme part of the URI is the one defined in its configuration.
*
* <p>On the events of requests obtaining a token for an existing client, for example {@code SERVICE_ACCOUNT_TOKEN_REQUEST},
* {@code IMPLICIT_HYBRID_TOKEN_RESPONSE} of a login finished through the login actions and {@code PERMISSION_TOKEN_REQUEST} of UMA,
* it checks the client ID of the client in the same way, so that the CIMD executor can enforce its policies on them, too.
*
* @author <a href="mailto:takashi.norimatsu.ws@hitachi.com">Takashi Norimatsu</a>
*/
public class ClientIdUriSchemeCondition extends AbstractClientPolicyConditionProvider<ClientIdUriSchemeCondition.Configuration> {
Expand Down Expand Up @@ -78,6 +84,21 @@ public ClientPolicyVote applyPolicy(ClientPolicyContext context) throws ClientPo
case AUTHORIZATION_REQUEST_REDIRECT_URI:
clientId = ((AuthorizationRequestRedirectUriContext) context).getClient().getClientId();
break;
case TOKEN_REQUEST:
case TOKEN_REFRESH:
case SERVICE_ACCOUNT_TOKEN_REQUEST:
case RESOURCE_OWNER_PASSWORD_CREDENTIALS_REQUEST:
case TOKEN_EXCHANGE_REQUEST:
case JWT_AUTHORIZATION_GRANT:
case BACKCHANNEL_AUTHENTICATION_REQUEST:
case BACKCHANNEL_TOKEN_REQUEST:
case DEVICE_AUTHORIZATION_REQUEST:
case DEVICE_TOKEN_REQUEST:
case IMPLICIT_HYBRID_TOKEN_RESPONSE:
case PERMISSION_TOKEN_REQUEST:
ClientModel client = getClient(context, session);
clientId = client == null ? null : client.getClientId();
break;
default:
return ClientPolicyVote.ABSTAIN;
}
Expand All @@ -96,6 +117,19 @@ public ClientPolicyVote applyPolicy(ClientPolicyContext context) throws ClientPo
return ClientPolicyVote.NO;
}

/**
* Returns the client of a request obtaining a token, which has been already authenticated.
*
* @param context a client policy context
* @return {@code ClientModel} the client, {@code null} if not resolved
*/
public static ClientModel getClient(ClientPolicyContext context, KeycloakSession session) {
if (context instanceof ClientModelContext clientModelContext && clientModelContext.getClient() != null) {
return clientModelContext.getClient();
}
return session.getContext().getClient();
}

private boolean isUriSchemeMatched(URI uri) {
return configuration.getClientIdUriSchemes().stream().anyMatch(i->i.equals(uri.getScheme()));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ public String getId() {
@Override
public String getHelpText() {
return "The condition checks that the scheme part of client_id parameter matches one of the filled ones " +
"and the host part of the client_id matches one of the filled domains.";
"and the host part of the client_id matches one of the filled domains. " +
"On a request obtaining a token, including the token response of the implicit or hybrid flow and a UMA permission request, the condition checks the client ID of the client in the same way.";
}

@Override
Expand Down
Loading
Loading