Missing client_id validation match when authenticating client with JW… (#22178)
Closes #22177
This commit is contained in:
parent
5c6df3d26e
commit
4dc929abb3
5 changed files with 276 additions and 211 deletions
|
@ -17,15 +17,12 @@
|
||||||
|
|
||||||
package org.keycloak.authentication.authenticators.client;
|
package org.keycloak.authentication.authenticators.client;
|
||||||
|
|
||||||
import org.keycloak.http.HttpRequest;
|
|
||||||
import org.keycloak.Config;
|
import org.keycloak.Config;
|
||||||
import org.keycloak.authentication.ClientAuthenticator;
|
import org.keycloak.authentication.ClientAuthenticator;
|
||||||
import org.keycloak.authentication.ClientAuthenticatorFactory;
|
import org.keycloak.authentication.ClientAuthenticatorFactory;
|
||||||
import org.keycloak.models.KeycloakSession;
|
import org.keycloak.models.KeycloakSession;
|
||||||
import org.keycloak.models.KeycloakSessionFactory;
|
import org.keycloak.models.KeycloakSessionFactory;
|
||||||
|
|
||||||
import jakarta.ws.rs.core.MediaType;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
|
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
|
||||||
*/
|
*/
|
||||||
|
@ -65,9 +62,4 @@ public abstract class AbstractClientAuthenticator implements ClientAuthenticator
|
||||||
public String getReferenceCategory() {
|
public String getReferenceCategory() {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected boolean isFormDataRequest(HttpRequest request) {
|
|
||||||
MediaType mediaType = request.getHttpHeaders().getMediaType();
|
|
||||||
return mediaType != null && mediaType.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,22 +29,16 @@ import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
import jakarta.ws.rs.core.MultivaluedMap;
|
|
||||||
import jakarta.ws.rs.core.Response;
|
import jakarta.ws.rs.core.Response;
|
||||||
|
|
||||||
import org.jboss.logging.Logger;
|
|
||||||
import org.keycloak.OAuth2Constants;
|
|
||||||
import org.keycloak.OAuthErrorException;
|
import org.keycloak.OAuthErrorException;
|
||||||
import org.keycloak.authentication.AuthenticationFlowError;
|
import org.keycloak.authentication.AuthenticationFlowError;
|
||||||
import org.keycloak.authentication.ClientAuthenticationFlowContext;
|
import org.keycloak.authentication.ClientAuthenticationFlowContext;
|
||||||
import org.keycloak.common.util.Time;
|
|
||||||
import org.keycloak.jose.jws.JWSInput;
|
import org.keycloak.jose.jws.JWSInput;
|
||||||
import org.keycloak.keys.loader.PublicKeyStorageManager;
|
import org.keycloak.keys.loader.PublicKeyStorageManager;
|
||||||
import org.keycloak.models.AuthenticationExecutionModel;
|
import org.keycloak.models.AuthenticationExecutionModel;
|
||||||
import org.keycloak.models.ClientModel;
|
import org.keycloak.models.ClientModel;
|
||||||
import org.keycloak.models.RealmModel;
|
import org.keycloak.models.RealmModel;
|
||||||
import org.keycloak.models.SingleUseObjectProvider;
|
|
||||||
import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;
|
|
||||||
import org.keycloak.protocol.oidc.OIDCConfigAttributes;
|
import org.keycloak.protocol.oidc.OIDCConfigAttributes;
|
||||||
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
|
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
|
||||||
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
|
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
|
||||||
|
@ -66,8 +60,6 @@ import org.keycloak.services.Urls;
|
||||||
*/
|
*/
|
||||||
public class JWTClientAuthenticator extends AbstractClientAuthenticator {
|
public class JWTClientAuthenticator extends AbstractClientAuthenticator {
|
||||||
|
|
||||||
private static final Logger logger = Logger.getLogger(JWTClientAuthenticator.class);
|
|
||||||
|
|
||||||
public static final String PROVIDER_ID = "client-jwt";
|
public static final String PROVIDER_ID = "client-jwt";
|
||||||
public static final String ATTR_PREFIX = "jwt.credential";
|
public static final String ATTR_PREFIX = "jwt.credential";
|
||||||
public static final String CERTIFICATE_ATTR = "jwt.credential.certificate";
|
public static final String CERTIFICATE_ATTR = "jwt.credential.certificate";
|
||||||
|
@ -75,79 +67,19 @@ public class JWTClientAuthenticator extends AbstractClientAuthenticator {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void authenticateClient(ClientAuthenticationFlowContext context) {
|
public void authenticateClient(ClientAuthenticationFlowContext context) {
|
||||||
|
JWTClientValidator validator = new JWTClientValidator(context);
|
||||||
//KEYCLOAK-19461: Needed for quarkus resteasy implementation throws exception when called with mediaType authentication/json in OpenShiftTokenReviewEndpoint
|
if (!validator.clientAssertionParametersValidation()) return;
|
||||||
if(!isFormDataRequest(context.getHttpRequest())) {
|
|
||||||
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "Parameter client_assertion_type is missing");
|
|
||||||
context.challenge(challengeResponse);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
MultivaluedMap<String, String> params = context.getHttpRequest().getDecodedFormParameters();
|
|
||||||
|
|
||||||
String clientAssertionType = params.getFirst(OAuth2Constants.CLIENT_ASSERTION_TYPE);
|
|
||||||
String clientAssertion = params.getFirst(OAuth2Constants.CLIENT_ASSERTION);
|
|
||||||
|
|
||||||
if (clientAssertionType == null) {
|
|
||||||
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "Parameter client_assertion_type is missing");
|
|
||||||
context.challenge(challengeResponse);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!clientAssertionType.equals(OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT)) {
|
|
||||||
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "Parameter client_assertion_type has value '"
|
|
||||||
+ clientAssertionType + "' but expected is '" + OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT + "'");
|
|
||||||
context.challenge(challengeResponse);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (clientAssertion == null) {
|
|
||||||
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "client_assertion parameter missing");
|
|
||||||
context.failure(AuthenticationFlowError.INVALID_CLIENT_CREDENTIALS, challengeResponse);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
JWSInput jws = new JWSInput(clientAssertion);
|
validator.readJws();
|
||||||
JsonWebToken token = jws.readJsonContent(JsonWebToken.class);
|
if (!validator.validateClient()) return;
|
||||||
|
if (!validator.validateSignatureAlgorithm()) return;
|
||||||
|
|
||||||
RealmModel realm = context.getRealm();
|
RealmModel realm = validator.getRealm();
|
||||||
String clientId = token.getSubject();
|
ClientModel client = validator.getClient();
|
||||||
if (clientId == null) {
|
JWSInput jws = validator.getJws();
|
||||||
throw new RuntimeException("Can't identify client. Subject missing on JWT token");
|
JsonWebToken token = validator.getToken();
|
||||||
}
|
String clientAssertion = validator.getClientAssertion();
|
||||||
|
|
||||||
if (!clientId.equals(token.getIssuer())) {
|
|
||||||
throw new RuntimeException("Issuer mismatch. The issuer should match the subject");
|
|
||||||
}
|
|
||||||
|
|
||||||
context.getEvent().client(clientId);
|
|
||||||
ClientModel client = realm.getClientByClientId(clientId);
|
|
||||||
if (client == null) {
|
|
||||||
context.failure(AuthenticationFlowError.CLIENT_NOT_FOUND, null);
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
context.setClient(client);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!client.isEnabled()) {
|
|
||||||
context.failure(AuthenticationFlowError.CLIENT_DISABLED, null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
String expectedSignatureAlg = OIDCAdvancedConfigWrapper.fromClientModel(client).getTokenEndpointAuthSigningAlg();
|
|
||||||
if (jws.getHeader().getAlgorithm() == null || jws.getHeader().getAlgorithm().name() == null) {
|
|
||||||
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "invalid signature algorithm");
|
|
||||||
context.challenge(challengeResponse);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
String actualSignatureAlg = jws.getHeader().getAlgorithm().name();
|
|
||||||
if (expectedSignatureAlg != null && !expectedSignatureAlg.equals(actualSignatureAlg)) {
|
|
||||||
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "invalid signature algorithm");
|
|
||||||
context.challenge(challengeResponse);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get client key and validate signature
|
// Get client key and validate signature
|
||||||
PublicKey clientPublicKey = getSignatureValidationKey(client, context, jws);
|
PublicKey clientPublicKey = getSignatureValidationKey(client, context, jws);
|
||||||
|
@ -176,29 +108,8 @@ public class JWTClientAuthenticator extends AbstractClientAuthenticator {
|
||||||
+ " but audience from token is '" + Arrays.asList(token.getAudience()) + "'");
|
+ " but audience from token is '" + Arrays.asList(token.getAudience()) + "'");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!token.isActive()) {
|
validator.validateToken();
|
||||||
throw new RuntimeException("Token is not active");
|
validator.validateTokenReuse();
|
||||||
}
|
|
||||||
|
|
||||||
// KEYCLOAK-2986
|
|
||||||
int currentTime = Time.currentTime();
|
|
||||||
if (token.getExpiration() == 0 && token.getIssuedAt() + 10 < currentTime) {
|
|
||||||
throw new RuntimeException("Token is not active");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (token.getId() == null) {
|
|
||||||
throw new RuntimeException("Missing ID on the token");
|
|
||||||
}
|
|
||||||
|
|
||||||
SingleUseObjectProvider singleUseCache = context.getSession().singleUseObjects();
|
|
||||||
int lifespanInSecs = Math.max(token.getExpiration() - currentTime, 10);
|
|
||||||
if (singleUseCache.putIfAbsent(token.getId(), lifespanInSecs)) {
|
|
||||||
logger.tracef("Added token '%s' to single-use cache. Lifespan: %d seconds, client: %s", token.getId(), lifespanInSecs, clientId);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
logger.warnf("Token '%s' already used when authenticating client '%s'.", token.getId(), clientId);
|
|
||||||
throw new RuntimeException("Token reuse detected");
|
|
||||||
}
|
|
||||||
|
|
||||||
context.success();
|
context.success();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
|
|
@ -16,17 +16,12 @@
|
||||||
*/
|
*/
|
||||||
package org.keycloak.authentication.authenticators.client;
|
package org.keycloak.authentication.authenticators.client;
|
||||||
|
|
||||||
import org.jboss.logging.Logger;
|
|
||||||
import org.keycloak.OAuth2Constants;
|
|
||||||
import org.keycloak.authentication.AuthenticationFlowError;
|
import org.keycloak.authentication.AuthenticationFlowError;
|
||||||
import org.keycloak.authentication.ClientAuthenticationFlowContext;
|
import org.keycloak.authentication.ClientAuthenticationFlowContext;
|
||||||
import org.keycloak.common.util.Time;
|
|
||||||
import org.keycloak.jose.jws.JWSInput;
|
import org.keycloak.jose.jws.JWSInput;
|
||||||
import org.keycloak.models.AuthenticationExecutionModel.Requirement;
|
import org.keycloak.models.AuthenticationExecutionModel.Requirement;
|
||||||
import org.keycloak.models.ClientModel;
|
import org.keycloak.models.ClientModel;
|
||||||
import org.keycloak.models.RealmModel;
|
import org.keycloak.models.RealmModel;
|
||||||
import org.keycloak.models.SingleUseObjectProvider;
|
|
||||||
import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;
|
|
||||||
import org.keycloak.protocol.oidc.OIDCClientSecretConfigWrapper;
|
import org.keycloak.protocol.oidc.OIDCClientSecretConfigWrapper;
|
||||||
import org.keycloak.protocol.oidc.OIDCConfigAttributes;
|
import org.keycloak.protocol.oidc.OIDCConfigAttributes;
|
||||||
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
|
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
|
||||||
|
@ -36,7 +31,6 @@ import org.keycloak.representations.JsonWebToken;
|
||||||
import org.keycloak.services.ServicesLogger;
|
import org.keycloak.services.ServicesLogger;
|
||||||
import org.keycloak.services.Urls;
|
import org.keycloak.services.Urls;
|
||||||
|
|
||||||
import jakarta.ws.rs.core.MultivaluedMap;
|
|
||||||
import jakarta.ws.rs.core.Response;
|
import jakarta.ws.rs.core.Response;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
|
@ -54,89 +48,26 @@ import java.util.Set;
|
||||||
* This is server side, which verifies JWT from client_assertion parameter, where the assertion was created on adapter side by
|
* This is server side, which verifies JWT from client_assertion parameter, where the assertion was created on adapter side by
|
||||||
* org.keycloak.adapters.authentication.JWTClientSecretCredentialsProvider
|
* org.keycloak.adapters.authentication.JWTClientSecretCredentialsProvider
|
||||||
* <p>
|
* <p>
|
||||||
* TODO: Try to create abstract superclass to be shared with {@link JWTClientAuthenticator}. Most of the code can be reused
|
|
||||||
*/
|
*/
|
||||||
public class JWTClientSecretAuthenticator extends AbstractClientAuthenticator {
|
public class JWTClientSecretAuthenticator extends AbstractClientAuthenticator {
|
||||||
|
|
||||||
private static final Logger logger = Logger.getLogger(JWTClientSecretAuthenticator.class);
|
|
||||||
|
|
||||||
public static final String PROVIDER_ID = "client-secret-jwt";
|
public static final String PROVIDER_ID = "client-secret-jwt";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void authenticateClient(ClientAuthenticationFlowContext context) {
|
public void authenticateClient(ClientAuthenticationFlowContext context) {
|
||||||
|
JWTClientValidator validator = new JWTClientValidator(context);
|
||||||
//KEYCLOAK-19461: Needed for quarkus resteasy implementation throws exception when called with mediaType authentication/json in OpenShiftTokenReviewEndpoint
|
if (!validator.clientAssertionParametersValidation()) return;
|
||||||
if (!isFormDataRequest(context.getHttpRequest())) {
|
|
||||||
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "Parameter client_assertion_type is missing");
|
|
||||||
context.challenge(challengeResponse);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
MultivaluedMap<String, String> params = context.getHttpRequest().getDecodedFormParameters();
|
|
||||||
|
|
||||||
String clientAssertionType = params.getFirst(OAuth2Constants.CLIENT_ASSERTION_TYPE);
|
|
||||||
String clientAssertion = params.getFirst(OAuth2Constants.CLIENT_ASSERTION);
|
|
||||||
|
|
||||||
if (clientAssertionType == null) {
|
|
||||||
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "Parameter client_assertion_type is missing");
|
|
||||||
context.challenge(challengeResponse);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!clientAssertionType.equals(OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT)) {
|
|
||||||
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "Parameter client_assertion_type has value '"
|
|
||||||
+ clientAssertionType + "' but expected is '" + OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT + "'");
|
|
||||||
context.challenge(challengeResponse);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (clientAssertion == null) {
|
|
||||||
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "client_assertion parameter missing");
|
|
||||||
context.failure(AuthenticationFlowError.INVALID_CLIENT_CREDENTIALS, challengeResponse);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
JWSInput jws = new JWSInput(clientAssertion);
|
validator.readJws();
|
||||||
JsonWebToken token = jws.readJsonContent(JsonWebToken.class);
|
if (!validator.validateClient()) return;
|
||||||
|
if (!validator.validateSignatureAlgorithm()) return;
|
||||||
|
|
||||||
RealmModel realm = context.getRealm();
|
RealmModel realm = validator.getRealm();
|
||||||
String clientId = token.getSubject();
|
ClientModel client = validator.getClient();
|
||||||
if (clientId == null) {
|
JWSInput jws = validator.getJws();
|
||||||
throw new RuntimeException("Can't identify client. Subject missing on JWT token");
|
JsonWebToken token = validator.getToken();
|
||||||
}
|
String clientAssertion = validator.getClientAssertion();
|
||||||
|
|
||||||
if (!clientId.equals(token.getIssuer())) {
|
|
||||||
throw new RuntimeException("Issuer mismatch. The issuer should match the subject");
|
|
||||||
}
|
|
||||||
|
|
||||||
context.getEvent().client(clientId);
|
|
||||||
ClientModel client = realm.getClientByClientId(clientId);
|
|
||||||
if (client == null) {
|
|
||||||
context.failure(AuthenticationFlowError.CLIENT_NOT_FOUND, null);
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
context.setClient(client);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!client.isEnabled()) {
|
|
||||||
context.failure(AuthenticationFlowError.CLIENT_DISABLED, null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
String expectedSignatureAlg = OIDCAdvancedConfigWrapper.fromClientModel(client).getTokenEndpointAuthSigningAlg();
|
|
||||||
if (jws.getHeader().getAlgorithm() == null || jws.getHeader().getAlgorithm().name() == null) {
|
|
||||||
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "invalid signature algorithm");
|
|
||||||
context.challenge(challengeResponse);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
String actualSignatureAlg = jws.getHeader().getAlgorithm().name();
|
|
||||||
if (expectedSignatureAlg != null && !expectedSignatureAlg.equals(actualSignatureAlg)) {
|
|
||||||
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "invalid signature algorithm");
|
|
||||||
context.challenge(challengeResponse);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
String clientSecretString = client.getSecret();
|
String clientSecretString = client.getSecret();
|
||||||
if (clientSecretString == null) {
|
if (clientSecretString == null) {
|
||||||
|
@ -178,29 +109,8 @@ public class JWTClientSecretAuthenticator extends AbstractClientAuthenticator {
|
||||||
throw new RuntimeException("Token audience doesn't match domain. Realm issuer is '" + issuerUrl + "' but audience from token is '" + Arrays.asList(token.getAudience()).toString() + "'");
|
throw new RuntimeException("Token audience doesn't match domain. Realm issuer is '" + issuerUrl + "' but audience from token is '" + Arrays.asList(token.getAudience()).toString() + "'");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!token.isActive()) {
|
validator.validateToken();
|
||||||
throw new RuntimeException("Token is not active");
|
validator.validateTokenReuse();
|
||||||
}
|
|
||||||
|
|
||||||
// KEYCLOAK-2986, token-timeout or token-expiration in keycloak.json might not be used
|
|
||||||
int currentTime = Time.currentTime();
|
|
||||||
if (token.getExpiration() == 0 && token.getIssuedAt() + 10 < currentTime) {
|
|
||||||
throw new RuntimeException("Token is not active");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (token.getId() == null) {
|
|
||||||
throw new RuntimeException("Missing ID on the token");
|
|
||||||
}
|
|
||||||
|
|
||||||
SingleUseObjectProvider singleUseCache = context.getSession().singleUseObjects();
|
|
||||||
int lifespanInSecs = Math.max(token.getExpiration() - currentTime, 10);
|
|
||||||
if (singleUseCache.putIfAbsent(token.getId(), lifespanInSecs)) {
|
|
||||||
|
|
||||||
logger.tracef("Added token '%s' to single-use cache. Lifespan: %d seconds, client: %s", token.getId(), lifespanInSecs, clientId);
|
|
||||||
} else {
|
|
||||||
logger.warnf("Token '%s' already used when authenticating client '%s'.", token.getId(), clientId);
|
|
||||||
throw new RuntimeException("Token reuse detected");
|
|
||||||
}
|
|
||||||
|
|
||||||
context.success();
|
context.success();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
|
|
@ -0,0 +1,225 @@
|
||||||
|
/*
|
||||||
|
* Copyright 2023 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.authentication.authenticators.client;
|
||||||
|
|
||||||
|
import jakarta.ws.rs.core.MediaType;
|
||||||
|
import jakarta.ws.rs.core.MultivaluedMap;
|
||||||
|
import jakarta.ws.rs.core.Response;
|
||||||
|
import org.jboss.logging.Logger;
|
||||||
|
import org.keycloak.OAuth2Constants;
|
||||||
|
import org.keycloak.authentication.AuthenticationFlowError;
|
||||||
|
import org.keycloak.authentication.ClientAuthenticationFlowContext;
|
||||||
|
import org.keycloak.common.util.Time;
|
||||||
|
import org.keycloak.http.HttpRequest;
|
||||||
|
import org.keycloak.jose.jws.JWSInput;
|
||||||
|
import org.keycloak.jose.jws.JWSInputException;
|
||||||
|
import org.keycloak.models.ClientModel;
|
||||||
|
import org.keycloak.models.RealmModel;
|
||||||
|
import org.keycloak.models.SingleUseObjectProvider;
|
||||||
|
import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;
|
||||||
|
import org.keycloak.representations.JsonWebToken;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Common validation for JWT client authentication with private_key_jwt or with client_secret
|
||||||
|
*
|
||||||
|
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
|
||||||
|
*/
|
||||||
|
public class JWTClientValidator {
|
||||||
|
|
||||||
|
private static final Logger logger = Logger.getLogger(JWTClientValidator.class);
|
||||||
|
|
||||||
|
private final ClientAuthenticationFlowContext context;
|
||||||
|
private final RealmModel realm;
|
||||||
|
private final int currentTime;
|
||||||
|
|
||||||
|
private MultivaluedMap<String, String> params;
|
||||||
|
private String clientAssertion;
|
||||||
|
private JWSInput jws;
|
||||||
|
private JsonWebToken token;
|
||||||
|
private ClientModel client;
|
||||||
|
|
||||||
|
public JWTClientValidator(ClientAuthenticationFlowContext context) {
|
||||||
|
this.context = context;
|
||||||
|
this.realm = context.getRealm();
|
||||||
|
this.currentTime = Time.currentTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean clientAssertionParametersValidation() {
|
||||||
|
//KEYCLOAK-19461: Needed for quarkus resteasy implementation throws exception when called with mediaType authentication/json in OpenShiftTokenReviewEndpoint
|
||||||
|
if(!isFormDataRequest(context.getHttpRequest())) {
|
||||||
|
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "Parameter client_assertion_type is missing");
|
||||||
|
context.challenge(challengeResponse);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
params = context.getHttpRequest().getDecodedFormParameters();
|
||||||
|
|
||||||
|
String clientAssertionType = params.getFirst(OAuth2Constants.CLIENT_ASSERTION_TYPE);
|
||||||
|
clientAssertion = params.getFirst(OAuth2Constants.CLIENT_ASSERTION);
|
||||||
|
|
||||||
|
if (clientAssertionType == null) {
|
||||||
|
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "Parameter client_assertion_type is missing");
|
||||||
|
context.challenge(challengeResponse);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!clientAssertionType.equals(OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT)) {
|
||||||
|
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "Parameter client_assertion_type has value '"
|
||||||
|
+ clientAssertionType + "' but expected is '" + OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT + "'");
|
||||||
|
context.challenge(challengeResponse);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (clientAssertion == null) {
|
||||||
|
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "client_assertion parameter missing");
|
||||||
|
context.failure(AuthenticationFlowError.INVALID_CLIENT_CREDENTIALS, challengeResponse);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void readJws() throws JWSInputException {
|
||||||
|
if (clientAssertion == null) throw new IllegalStateException("Incorrect usage. Variable 'clientAssertion' is null. Need to validate clientAssertion first before read JWS");
|
||||||
|
|
||||||
|
jws = new JWSInput(clientAssertion);
|
||||||
|
token = jws.readJsonContent(JsonWebToken.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean validateClient() {
|
||||||
|
if (token == null) throw new IllegalStateException("Incorrect usage. Variable 'token' is null. Need to read JWS first before validateClient");
|
||||||
|
|
||||||
|
String clientId = token.getSubject();
|
||||||
|
if (clientId == null) {
|
||||||
|
throw new RuntimeException("Can't identify client. Subject missing on JWT token");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!clientId.equals(token.getIssuer())) {
|
||||||
|
throw new RuntimeException("Issuer mismatch. The issuer should match the subject");
|
||||||
|
}
|
||||||
|
|
||||||
|
String clientIdParam = params.getFirst(OAuth2Constants.CLIENT_ID);
|
||||||
|
if (clientIdParam != null && !clientIdParam.equals(clientId)) {
|
||||||
|
throw new RuntimeException("client_id parameter not matching with client from JWT token");
|
||||||
|
}
|
||||||
|
|
||||||
|
context.getEvent().client(clientId);
|
||||||
|
client = realm.getClientByClientId(clientId);
|
||||||
|
if (client == null) {
|
||||||
|
context.failure(AuthenticationFlowError.CLIENT_NOT_FOUND, null);
|
||||||
|
return false;
|
||||||
|
} else {
|
||||||
|
context.setClient(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!client.isEnabled()) {
|
||||||
|
context.failure(AuthenticationFlowError.CLIENT_DISABLED, null);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean validateSignatureAlgorithm() {
|
||||||
|
if (jws == null) throw new IllegalStateException("Incorrect usage. Variable 'jws' is null. Need to read token first before validate signature algorithm");
|
||||||
|
if (client == null) throw new IllegalStateException("Incorrect usage. Variable 'client' is null. Need to validate client first before validate signature algorithm");
|
||||||
|
|
||||||
|
String expectedSignatureAlg = OIDCAdvancedConfigWrapper.fromClientModel(client).getTokenEndpointAuthSigningAlg();
|
||||||
|
if (jws.getHeader().getAlgorithm() == null || jws.getHeader().getAlgorithm().name() == null) {
|
||||||
|
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "invalid signature algorithm");
|
||||||
|
context.challenge(challengeResponse);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
String actualSignatureAlg = jws.getHeader().getAlgorithm().name();
|
||||||
|
if (expectedSignatureAlg != null && !expectedSignatureAlg.equals(actualSignatureAlg)) {
|
||||||
|
Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "invalid signature algorithm");
|
||||||
|
context.challenge(challengeResponse);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void validateToken() {
|
||||||
|
if (token == null) throw new IllegalStateException("Incorrect usage. Variable 'token' is null. Need to read token first before validateToken");
|
||||||
|
|
||||||
|
if (!token.isActive()) {
|
||||||
|
throw new RuntimeException("Token is not active");
|
||||||
|
}
|
||||||
|
|
||||||
|
// KEYCLOAK-2986, token-timeout or token-expiration in keycloak.json might not be used
|
||||||
|
if (token.getExpiration() == 0 && token.getIssuedAt() + 10 < currentTime) {
|
||||||
|
throw new RuntimeException("Token is not active");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (token.getId() == null) {
|
||||||
|
throw new RuntimeException("Missing ID on the token");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void validateTokenReuse() {
|
||||||
|
if (token == null) throw new IllegalStateException("Incorrect usage. Variable 'token' is null. Need to read token first before validateToken reuse");
|
||||||
|
if (client == null) throw new IllegalStateException("Incorrect usage. Variable 'client' is null. Need to validate client first before validateToken reuse");
|
||||||
|
|
||||||
|
SingleUseObjectProvider singleUseCache = context.getSession().singleUseObjects();
|
||||||
|
int lifespanInSecs = Math.max(token.getExpiration() - currentTime, 10);
|
||||||
|
if (singleUseCache.putIfAbsent(token.getId(), lifespanInSecs)) {
|
||||||
|
logger.tracef("Added token '%s' to single-use cache. Lifespan: %d seconds, client: %s", token.getId(), lifespanInSecs, client.getClientId());
|
||||||
|
|
||||||
|
} else {
|
||||||
|
logger.warnf("Token '%s' already used when authenticating client '%s'.", token.getId(), client.getClientId());
|
||||||
|
throw new RuntimeException("Token reuse detected");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public ClientAuthenticationFlowContext getContext() {
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
|
||||||
|
public RealmModel getRealm() {
|
||||||
|
return realm;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MultivaluedMap<String, String> getParams() {
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getClientAssertion() {
|
||||||
|
return clientAssertion;
|
||||||
|
}
|
||||||
|
|
||||||
|
public JWSInput getJws() {
|
||||||
|
return jws;
|
||||||
|
}
|
||||||
|
|
||||||
|
public JsonWebToken getToken() {
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ClientModel getClient() {
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isFormDataRequest(HttpRequest request) {
|
||||||
|
MediaType mediaType = request.getHttpHeaders().getMediaType();
|
||||||
|
return mediaType != null && mediaType.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
||||||
|
}
|
||||||
|
}
|
|
@ -887,6 +887,33 @@ public class ClientAuthSignedJWTTest extends AbstractKeycloakTest {
|
||||||
assertError(response,401, "unknown-client", "invalid_client", Errors.CLIENT_NOT_FOUND);
|
assertError(response,401, "unknown-client", "invalid_client", Errors.CLIENT_NOT_FOUND);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testAssertionNonMatchingClientIdParameter() throws Exception {
|
||||||
|
String invalidJwt = getClient1SignedJWT();
|
||||||
|
|
||||||
|
// client_id parameter does not match the client from JWT (See "client_id" at https://www.rfc-editor.org/rfc/rfc7521.html#section-4.2 )
|
||||||
|
List<NameValuePair> parameters = new LinkedList<NameValuePair>();
|
||||||
|
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.CLIENT_CREDENTIALS));
|
||||||
|
parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION_TYPE, OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT));
|
||||||
|
parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION, invalidJwt));
|
||||||
|
parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ID, "client2"));
|
||||||
|
|
||||||
|
CloseableHttpResponse resp = sendRequest(oauth.getServiceAccountUrl(), parameters);
|
||||||
|
OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(resp);
|
||||||
|
|
||||||
|
assertError(response,"client2", "invalid_client", Errors.INVALID_CLIENT_CREDENTIALS);
|
||||||
|
|
||||||
|
// Matching client_id should work fine
|
||||||
|
parameters.remove(3);
|
||||||
|
parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ID, "client1"));
|
||||||
|
resp = sendRequest(oauth.getServiceAccountUrl(), parameters);
|
||||||
|
response = new OAuthClient.AccessTokenResponse(resp);
|
||||||
|
|
||||||
|
assertEquals(200, response.getStatusCode());
|
||||||
|
AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
|
||||||
|
assertEquals(accessToken.getIssuedFor(), "client1");
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAssertionDisabledClient() throws Exception {
|
public void testAssertionDisabledClient() throws Exception {
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue