diff --git a/services/src/main/java/org/keycloak/services/managers/ClientSessionCode.java b/services/src/main/java/org/keycloak/services/managers/ClientSessionCode.java index 32305b12da..46bba42fbe 100755 --- a/services/src/main/java/org/keycloak/services/managers/ClientSessionCode.java +++ b/services/src/main/java/org/keycloak/services/managers/ClientSessionCode.java @@ -102,10 +102,9 @@ public class ClientSessionCode { Set requestedRoles = new HashSet(); for (String roleId : clientSession.getRoles()) { RoleModel role = realm.getRoleById(roleId); - if (role == null) { - new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid role " + roleId); + if (role != null) { + requestedRoles.add(realm.getRoleById(roleId)); } - requestedRoles.add(realm.getRoleById(roleId)); } return requestedRoles; } diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/oauth/AccessTokenTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/oauth/AccessTokenTest.java index 144cc46a0e..27c2e51449 100755 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/oauth/AccessTokenTest.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/oauth/AccessTokenTest.java @@ -34,6 +34,7 @@ import org.keycloak.models.ApplicationModel; import org.keycloak.models.ClientModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; +import org.keycloak.models.RoleModel; import org.keycloak.models.UserModel; import org.keycloak.protocol.oidc.OpenIDConnectService; import org.keycloak.representations.AccessToken; @@ -234,6 +235,42 @@ public class AccessTokenTest { }); } + @Test + public void accessTokenCodeRoleMissing() { + keycloakRule.configure(new KeycloakRule.KeycloakSetup() { + @Override + public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { + RoleModel role = appRealm.addRole("tmp-role"); + session.users().getUserByUsername("test-user@localhost", appRealm).grantRole(role); + } + }); + + oauth.doLogin("test-user@localhost", "password"); + + Event loginEvent = events.expectLogin().assertEvent(); + + loginEvent.getDetails().get(Details.CODE_ID); + + String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE); + + keycloakRule.configure(new KeycloakRule.KeycloakSetup() { + @Override + public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { + appRealm.removeRole(appRealm.getRole("tmp-role")); + } + }); + + OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password"); + + Assert.assertEquals(200, response.getStatusCode()); + + AccessToken token = oauth.verifyToken(response.getAccessToken()); + Assert.assertEquals(1, token.getRealmAccess().getRoles().size()); + Assert.assertTrue(token.getRealmAccess().isUserInRole("user")); + + events.clear(); + } + @Test public void accessTokenCodeHasRequiredAction() { keycloakRule.configure(new KeycloakRule.KeycloakSetup() {