Skip to content

Commit

Permalink
KEYCLOAK-19540 FAPI 2.0 Baseline : Reject Resource Owner Password Cre…
Browse files Browse the repository at this point in the history
…dentials Grant
  • Loading branch information
tnorimat authored and mposolda committed Oct 21, 2021
1 parent 44ec565 commit 263161f
Show file tree
Hide file tree
Showing 8 changed files with 288 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public enum ClientPolicyEvent {
BACKCHANNEL_TOKEN_REQUEST,
PUSHED_AUTHORIZATION_REQUEST,
DEVICE_AUTHORIZATION_REQUEST,
DEVICE_TOKEN_REQUEST
DEVICE_TOKEN_REQUEST,
RESOURCE_OWNER_PASSWORD_CREDENTIALS_REQUEST

}
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
import org.keycloak.services.ServicesLogger;
import org.keycloak.services.Urls;
import org.keycloak.services.clientpolicy.ClientPolicyException;
import org.keycloak.services.clientpolicy.context.ResourceOwnerPasswordCredentialsContext;
import org.keycloak.services.clientpolicy.context.ServiceAccountTokenRequestContext;
import org.keycloak.services.clientpolicy.context.TokenRefreshContext;
import org.keycloak.services.clientpolicy.context.TokenRequestContext;
Expand Down Expand Up @@ -630,6 +631,14 @@ public Response resourceOwnerPasswordCredentialsGrant() {
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);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Copyright 2021 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.services.clientpolicy.context;

import javax.ws.rs.core.MultivaluedMap;

import org.keycloak.services.clientpolicy.ClientPolicyContext;
import org.keycloak.services.clientpolicy.ClientPolicyEvent;

/**
* @author <a href="mailto:[email protected]">Takashi Norimatsu</a>
*/
public class ResourceOwnerPasswordCredentialsContext implements ClientPolicyContext {

private final MultivaluedMap<String, String> params;

public ResourceOwnerPasswordCredentialsContext(MultivaluedMap<String, String> params) {
this.params = params;
}

@Override
public ClientPolicyEvent getEvent() {
return ClientPolicyEvent.RESOURCE_OWNER_PASSWORD_CREDENTIALS_REQUEST;
}

public MultivaluedMap<String, String> getParams() {
return params;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
* Copyright 2021 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.services.clientpolicy.executor;

import javax.ws.rs.core.MultivaluedMap;

import org.keycloak.OAuthErrorException;
import org.keycloak.models.KeycloakSession;
import org.keycloak.representations.idm.ClientPolicyExecutorConfigurationRepresentation;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.services.clientpolicy.ClientPolicyContext;
import org.keycloak.services.clientpolicy.ClientPolicyException;
import org.keycloak.services.clientpolicy.context.ClientCRUDContext;
import org.keycloak.services.clientpolicy.context.ResourceOwnerPasswordCredentialsContext;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
* @author <a href="mailto:[email protected]">Takashi Norimatsu</a>
*/
public class RejectResourceOwnerPasswordCredentialsGrantExecutor implements ClientPolicyExecutorProvider<RejectResourceOwnerPasswordCredentialsGrantExecutor.Configuration> {

private final KeycloakSession session;
private Configuration configuration;

public RejectResourceOwnerPasswordCredentialsGrantExecutor(KeycloakSession session) {
this.session = session;
}

@Override
public void setupConfiguration(Configuration config) {
this.configuration = config;
}

@Override
public Class<Configuration> getExecutorConfigurationClass() {
return Configuration.class;
}

public static class Configuration extends ClientPolicyExecutorConfigurationRepresentation {
@JsonProperty("auto-configure")
protected Boolean autoConfigure;

public Boolean isAutoConfigure() {
return autoConfigure;
}

public void setAutoConfigure(Boolean autoConfigure) {
this.autoConfigure = autoConfigure;
}
}

@Override
public String getProviderId() {
return RejectResourceOwnerPasswordCredentialsGrantExecutorFactory.PROVIDER_ID;
}

@Override
public void executeOnEvent(ClientPolicyContext context) throws ClientPolicyException {
switch (context.getEvent()) {
case REGISTER:
case UPDATE:
ClientCRUDContext clientUpdateContext = (ClientCRUDContext)context;
autoConfigure(clientUpdateContext.getProposedClientRepresentation());
validate(clientUpdateContext.getProposedClientRepresentation());
break;
case RESOURCE_OWNER_PASSWORD_CREDENTIALS_REQUEST:
ResourceOwnerPasswordCredentialsContext ropcContext = (ResourceOwnerPasswordCredentialsContext)context;
executeOnAuthorizationRequest(ropcContext.getParams());
return;
default:
return;
}
}

private void autoConfigure(ClientRepresentation rep) {
if (configuration.isAutoConfigure())
rep.setDirectAccessGrantsEnabled(Boolean.FALSE);
}

private void validate(ClientRepresentation rep) throws ClientPolicyException {
boolean isResourceOwnerPasswordCredentialsGrantEnabled = rep.isDirectAccessGrantsEnabled().booleanValue();
if (!isResourceOwnerPasswordCredentialsGrantEnabled) return;
throw new ClientPolicyException(OAuthErrorException.INVALID_CLIENT_METADATA, "Invalid client metadata: resource owner password credentials grant enabled");
}

private void executeOnAuthorizationRequest(MultivaluedMap<String, String> params) throws ClientPolicyException {
// Before client policies operation, Token Endpoint logic has already checked whether resource owner password credentials grant is activated for a client.
// This method rejects resource owner password credentials grant regardless of client setting for allowing resource owner password credentials grant.
throw new ClientPolicyException(OAuthErrorException.INVALID_GRANT, "resource owner password credentials grant is prohibited.");
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright 2021 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.services.clientpolicy.executor;

import java.util.Collections;
import java.util.List;

import org.keycloak.Config.Scope;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.provider.ProviderConfigProperty;

/**
* @author <a href="mailto:[email protected]">Takashi Norimatsu</a>
*/
public class RejectResourceOwnerPasswordCredentialsGrantExecutorFactory implements ClientPolicyExecutorProviderFactory {

public static final String PROVIDER_ID = "reject-ropc-grant";

public static final String AUTO_CONFIGURE = "auto-configure";

private static final ProviderConfigProperty AUTO_CONFIGURE_PROPERTY = new ProviderConfigProperty(
AUTO_CONFIGURE, "Auto-configure", "If On, then the during client creation or update, the configuration of the client will be auto-configured to reject a resource owner password credentials grant.", ProviderConfigProperty.BOOLEAN_TYPE, false);

@Override
public ClientPolicyExecutorProvider create(KeycloakSession session) {
return new RejectResourceOwnerPasswordCredentialsGrantExecutor(session);
}

@Override
public void init(Scope config) {
}

@Override
public void postInit(KeycloakSessionFactory factory) {
}

@Override
public void close() {
}

@Override
public String getId() {
return PROVIDER_ID;
}

@Override
public String getHelpText() {
return "It makes keycloak to reject a resource owner password credentials grant.";
}

@Override
public List<ProviderConfigProperty> getConfigProperties() {
return Collections.singletonList(AUTO_CONFIGURE_PROPERTY);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ org.keycloak.services.clientpolicy.executor.FullScopeDisabledExecutorFactory
org.keycloak.protocol.oidc.grants.ciba.clientpolicy.executor.SecureCibaSessionEnforceExecutorFactory
org.keycloak.protocol.oidc.grants.ciba.clientpolicy.executor.SecureCibaSignedAuthenticationRequestExecutorFactory
org.keycloak.protocol.oidc.grants.ciba.clientpolicy.executor.SecureCibaAuthenticationRequestSigningAlgorithmExecutorFactory
org.keycloak.services.clientpolicy.executor.SecureLogoutExecutorFactory
org.keycloak.services.clientpolicy.executor.SecureLogoutExecutorFactory
org.keycloak.services.clientpolicy.executor.RejectResourceOwnerPasswordCredentialsGrantExecutorFactory
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
import org.keycloak.services.clientpolicy.executor.FullScopeDisabledExecutorFactory;
import org.keycloak.services.clientpolicy.executor.HolderOfKeyEnforcerExecutorFactory;
import org.keycloak.services.clientpolicy.executor.PKCEEnforcerExecutorFactory;
import org.keycloak.services.clientpolicy.executor.RejectResourceOwnerPasswordCredentialsGrantExecutorFactory;
import org.keycloak.services.clientpolicy.executor.SecureClientAuthenticatorExecutorFactory;
import org.keycloak.services.clientpolicy.executor.SecureClientUrisExecutorFactory;
import org.keycloak.services.clientpolicy.executor.SecureLogoutExecutorFactory;
Expand Down Expand Up @@ -148,6 +149,7 @@
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createSecureSigningAlgorithmForSignedJwtEnforceExecutorConfig;
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createTestRaiseExeptionConditionConfig;
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createFullScopeDisabledExecutorConfig;
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createRejectisResourceOwnerPasswordCredentialsGrantExecutorConfig;

import javax.ws.rs.BadRequestException;

Expand Down Expand Up @@ -2695,6 +2697,47 @@ public void testSecureLogoutExecutor() throws Exception {
assertTrue(driver.getPageSource().contains("Front-channel logout is not allowed for this client"));
}

@Test
public void testRejectResourceOwnerCredentialsGrantExecutor() throws Exception {

String clientId = generateSuffixedName(CLIENT_NAME);
String clientSecret = "secret";

createClientByAdmin(clientId, (ClientRepresentation clientRep) -> {
clientRep.setSecret(clientSecret);
clientRep.setStandardFlowEnabled(Boolean.TRUE);
clientRep.setDirectAccessGrantsEnabled(Boolean.TRUE);
clientRep.setPublicClient(Boolean.FALSE);
});

// register profiles
String json = (new ClientProfilesBuilder()).addProfile(
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Purofairu desu")
.addExecutor(RejectResourceOwnerPasswordCredentialsGrantExecutorFactory.PROVIDER_ID,
createRejectisResourceOwnerPasswordCredentialsGrantExecutorConfig(Boolean.TRUE))
.toRepresentation()
).toString();
updateProfiles(json);

// register policies
json = (new ClientPoliciesBuilder()).addPolicy(
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Porisii desu", Boolean.TRUE)
.addCondition(AnyClientConditionFactory.PROVIDER_ID,
createAnyClientConditionConfig())
.addProfile(PROFILE_NAME)
.toRepresentation()
).toString();
updatePolicies(json);

oauth.clientId(clientId);
OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest(clientSecret, TEST_USER_NAME, TEST_USER_PASSWORD, null);

assertEquals(400, response.getStatusCode());
assertEquals(OAuthErrorException.INVALID_GRANT, response.getError());
assertEquals("resource owner password credentials grant is prohibited.", response.getErrorDescription());

}

private void openVerificationPage(String verificationUri) {
driver.navigate().to(verificationUri);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import org.keycloak.services.clientpolicy.executor.FullScopeDisabledExecutor;
import org.keycloak.services.clientpolicy.executor.HolderOfKeyEnforcerExecutor;
import org.keycloak.services.clientpolicy.executor.PKCEEnforcerExecutor;
import org.keycloak.services.clientpolicy.executor.RejectResourceOwnerPasswordCredentialsGrantExecutor;
import org.keycloak.services.clientpolicy.executor.SecureClientAuthenticatorExecutor;
import org.keycloak.services.clientpolicy.executor.SecureRequestObjectExecutor;
import org.keycloak.services.clientpolicy.executor.SecureResponseTypeExecutor;
Expand Down Expand Up @@ -211,6 +212,12 @@ public static SecureCibaAuthenticationRequestSigningAlgorithmExecutor.Configurat
return config;
}

public static RejectResourceOwnerPasswordCredentialsGrantExecutor.Configuration createRejectisResourceOwnerPasswordCredentialsGrantExecutorConfig(Boolean autoConfigure) {
RejectResourceOwnerPasswordCredentialsGrantExecutor.Configuration config = new RejectResourceOwnerPasswordCredentialsGrantExecutor.Configuration();
config.setAutoConfigure(autoConfigure);
return config;
}

public static class ClientPoliciesBuilder {
private final ClientPoliciesRepresentation policiesRep;

Expand Down

0 comments on commit 263161f

Please sign in to comment.