8000 Customization for JWTAuthorizationGrantType to support ID-JAG by bucchi · Pull Request #46048 · keycloak/keycloak · GitHub
[go: up one dir, main page]

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions common/src/main/java/org/keycloak/common/Profile.java
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,8 @@ public enum Feature {

CIMD("OAuth Client ID Metadata Document", Type.EXPERIMENTAL),

IDENTITY_ASSERTION_JWT("Identity Assertion JWT", Type.EXPERIMENTAL),

/**
* @see <a href="https://github.com/keycloak/keycloak/issues/37967">Deprecate for removal the Instagram social broker</a>.
*/
Expand Down
4 changes: 4 additions & 0 deletions core/src/main/java/org/keycloak/OAuth2Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ public interface OAuth2Constants {
String JWT_AUTHORIZATION_GRANT = "urn:ietf:params:oauth:grant-type:jwt-bearer";
String ASSERTION = "assertion";

// https://datatracker.ietf.org/doc/draft-ietf-oauth-identity-assertion-authz-grant/
String IDENTITY_ASSERTION_JWT_HEADER_TYPE = "oauth-id-jag+jwt";


// https://tools.ietf.org/html/draft-ietf-oauth-assertions-01#page-5
String CLIENT_ASSERTION_TYPE = "client_assertion_type";
String CLIENT_ASSERTION = "client_assertion";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* Copyright 2025 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.Set;

import org.keycloak.OAuth2Constants;
import org.keycloak.authentication.authenticators.client.AbstractBaseJWTValidator;
import org.keycloak.authentication.authenticators.client.ClientAssertionState;
import org.keycloak.models.KeycloakSession;
import org.keycloak.protocol.oidc.OIDCConfigAttributes;
import org.keycloak.representations.IDToken;
import org.keycloak.representations.JsonWebToken;

/**
* the default assertion validator for JWT Authorization grant that extends AbstractBaseJWTValidator and
* implements the JWTAuthorizationGrantValidator interface, which extends the JWTAuthorizationGrantValidationContext interface.
*
* @author rmartinc
*/
public class DefaultJWTAuthorizationGrantValidator extends AbstractBaseJWTValidator implements JWTAuthorizationGrantValidator {

private final String scope;
private Set<String> restrictedScopes;

public static DefaultJWTAuthorizationGrantValidator createValidator(KeycloakSession session, String scope, ClientAssertionState clientAssertionState) {
return new DefaultJWTAuthorizationGrantValidator(session, scope, clientAssertionState);
}

protected DefaultJWTAuthorizationGrantValidator(KeycloakSession session, String scope, ClientAssertionState clientAssertionState) {
super(session, clientAssertionState);
this.scope = scope;
}

public void validateClient() {
if (clientAssertionState.getClient().isPublicClient()) {
failureCallback("Public client not allowed to use authorization grant");
}

String val = clientAssertionState.getClient().getAttribute(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_ENABLED);
if (!Boolean.parseBoolean(val)) {
throw new RuntimeException("JWT Authorization Grant is not supported for the requested client");
}
}

public void validateIssuer() {
if (getJWT().getIssuer() == null) {
failureCallback("Missing claim: " + OAuth2Constants.ISSUER);
}
}

public void validateSubject() {
if (getJWT().getSubject() == null) {
failureCallback("Missing claim: " + IDToken.SUBJECT);
}
}

@Override
public JsonWebToken getJWT() {
return clientAssertionState.getToken();
}

@Override
public String getAssertion() {
return clientAssertionState.getClientAssertion();
}

@Override
public String getScopeParam() {
return scope;
}

@Override
public Set<String> getRestrictedScopes() {
return restrictedScopes;
}

@Override
public void setRestrictedScopes(Set<String> restrictedScopes) {
this.restrictedScopes = restrictedScopes;
}

@Override
protected void failureCallback(String errorDescription) {
throw new RuntimeException(errorDescription);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright 2025 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.authentication.authenticators.client.ClientAssertionState;
import org.keycloak.models.KeycloakSession;
import org.keycloak.representations.JsonWebToken;

import org.jboss.logging.Logger;

/**
* the assertion validator for Identity Assertion JWT Authorization Grant (ID-JAG).
* Identity Assertion JWT is a new type of JWT that can be used as an authorization grant per RFC 7523.
*
* https://datatracker.ietf.org/doc/draft-ietf-oauth-identity-assertion-authz-grant/
*
* @author <a href="mailto:yutaka.obuchi.sd@hitachi.com">Yutaka Obuchi</a>
*/
public class IDJWTAuthorizationGrantValidator extends DefaultJWTAuthorizationGrantValidator {

private static final Logger logger = Logger.getLogger(IDJWTAuthorizationGrantValidator.class);

public static IDJWTAuthorizationGrantValidator createValidator(KeycloakSession session, String scope, ClientAssertionState clientAssertionState) {
return new IDJWTAuthorizationGrantValidator(session, scope, clientAssertionState);
}

private IDJWTAuthorizationGrantValidator(KeycloakSession session, String scope, ClientAssertionState clientAssertionState) {
super(session, scope, clientAssertionState);
}

public void validateClient() {
super.validateClient();

JsonWebToken accessToken = clientAssertionState.getToken();
String clientIdInToken = (String) accessToken.getOtherClaims().get("client_id");
String clientIdInRequestHeaderOrBody = session.getContext().getClient().getClientId();
if (clientIdInToken == null || !clientIdInRequestHeaderOrBody.equals(clientIdInToken)) {
logger.warn("client id in assertion : " + clientIdInToken + " and client id in request header/body : " + clientIdInRequestHeaderOrBody);
failureCallback("client id in assertion : " + clientIdInToken + " and client id in request header/body : " + clientIdInRequestHeaderOrBody);
return;
}
}

public boolean validateTokenActive(int allowedClockSkew, int maxExp, boolean reusePermitted) {

JsonWebToken accessToken = clientAssertionState.getToken();
if (accessToken.getIat() == null) {
failureCallback("Token iat claim is required");
return false;
}

if (reusePermitted) {
logger.warn("Token reuse is not permitted. Token reuse permitted setting is ignored.");
}

return super.validateTokenActive(allowedClockSkew, maxExp, false);

}

}
10678
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,12 @@
import org.keycloak.broker.provider.BrokeredIdentityContext;
import org.keycloak.broker.provider.JWTAuthorizationGrantProvider;
import org.keycloak.cache.AlternativeLookupProvider;
import org.keycloak.common.Profile;
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.ClientSessionContext;
import org.keycloak.models.FederatedIdentityModel;
Expand All @@ -40,6 +43,7 @@
import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.representations.JsonWebToken;
import org.keycloak.services.CorsErrorResponseException;
import org.keycloak.services.Urls;
import org.keycloak.services.clientpolicy.ClientPolicyException;
Expand All @@ -60,8 +64,33 @@ public Response process(Context context) {

try {

JWTAuthorizationGrantValidator authorizationGrantContext = JWTAuthorizationGrantValidator.createValidator(
context.getSession(), client, assertion, formParams.getFirst(OAuth2Constants.SCOPE));
if (assertion == null) {
throw new IllegalArgumentException("Missing parameter:" + OAuth2Constants.ASSERTION);
}

JWSInput jws;
JsonWebToken jwt;
try {
jws = new JWSInput(assertion);
jwt = jws.readJsonContent(JsonWebToken.class);
} catch (JWSInputException e) {
throw new RuntimeException("The provided assertion is not a valid JWT");
}

String jwtTokenType = jws.getHeader().getType();

ClientAssertionState clientAssertionState = new ClientAssertionState(OAuth2Constants.JWT_AUTHORIZATION_GRANT, assertion, jws, jwt);
clientAssertionState.setClient(context.getClient());

JWTAuthorizationGrantValidator authorizationGrantContext;
if (Profile.isFeatureEnabled(Profile.Feature.IDENTITY_ASSERTION_JWT) && jwtTokenType != null
&& jwtTokenType.equals(OAuth2Constants.IDENTITY_ASSERTION_JWT_HEADER_TYPE)) {
authorizationGrantContext = IDJWTAuthorizationGrantValidator.createValidator(
context.getSession(), formParams.getFirst(OAuth2Constants.SCOPE), clientAssertionState);
} else {
authorizationGrantContext = DefaultJWTAuthorizationGrantValidator.createValidator(
context.getSession(), formParams.getFirst(OAuth2Constants.SCOPE), clientAssertionState);
}
event.detail(Details.IDENTITY_PROVIDER_ISSUER, authorizationGrantContext.getIssuer());
event.detail(Details.IDENTITY_PROVIDER_USER_ID, authorizationGrantContext.getSubject());

Expand Down Expand Up @@ -109,7 +138,7 @@ public Response process(Context context) {

//user must exist in keycloak
FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(identityProviderModel.getAlias(), brokeredIdentityContext.getId(), brokeredIdentityContext.getUsername(), brokeredIdentityContext.getToken());
UserModel user = lookupUserByFederatedIdentity(federatedIdentityModel, authorizationGrantContext.getState());
UserModel user = lookupUserByFederatedIdentity(federatedIdentityModel, clientAssertionState);
if (user == null) {
throw new RuntimeException("User not found");
}
Expand Down
Loading
Loading
0