8000 Support for granular permissions in Account Console by cgeorgilakis · Pull Request #10568 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
8000
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,16 @@ public class MigrateTo20_0_0 implements Migration {
@Override
public void migrate(KeycloakSession session) {

session.realms().getRealmsStream().forEach(this::addViewGroupsRole);
session.realms().getRealmsStream().forEach(realm -> {
addViewGroupsRole(realm);
addAccountRoles(realm);
});
}

@Override
public void migrateImport(KeycloakSession session, RealmModel realm, RealmRepresentation rep, boolean skipUserDependent) {
addViewGroupsRole(realm);
addAccountRoles(realm);
}

private void addViewGroupsRole(RealmModel realm) {
Expand All @@ -34,6 +38,30 @@ private void addViewGroupsRole(RealmModel realm) {
}
}

private void addAccountRoles(RealmModel realm) {
ClientModel accountClient = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
RoleModel manageAccount = accountClient.getRole(AccountRoles.MANAGE_ACCOUNT);
if (accountClient != null && accountClient.getRole(AccountRoles.MANAGE_ACCOUNT_BASIC_AUTH) == null) {
RoleModel manageAccountBasicAuth = accountClient.addRole(AccountRoles.MANAGE_ACCOUNT_BASIC_AUTH);
manageAccountBasicAuth.setDescription("${role_" + AccountRoles.MANAGE_ACCOUNT_BASIC_AUTH + "}");
manageAccount.addCompositeRole(manageAccountBasicAuth);
}
if (accountClient != null && accountClient.getRole(AccountRoles.MANAGE_ACCOUNT_2FA) == null) {
RoleModel manageAccount2fa = accountClient.addRole(AccountRoles.MANAGE_ACCOUNT_2FA);
manageAccount2fa.setDescription("${role_" + AccountRoles.MANAGE_ACCOUNT_2FA + "}");
manageAccount.addCompositeRole(manageAccount2fa);
}
ClientModel accountConsoleClient = realm.getClientByClientId(Constants.ACCOUNT_CONSOLE_CLIENT_ID);
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.DELETE_ACCOUNT));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.MANAGE_ACCOUNT_2FA));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.MANAGE_ACCOUNT_BASIC_AUTH));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.MANAGE_ACCOUNT_LINKS));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.MANAGE_CONSENT));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.VIEW_APPLICATIONS));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.VIEW_CONSENT));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.VIEW_PROFILE));
}

@Override
public ModelVersion getVersion() {
return VERSION;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ public interface AccountRoles {
String VIEW_PROFILE = "view-profile";
String MANAGE_ACCOUNT = "manage-account";
String MANAGE_ACCOUNT_LINKS = "manage-account-links";
String MANAGE_ACCOUNT_BASIC_AUTH = "manage-account-basic-auth";
String MANAGE_ACCOUNT_2FA = "manage-account-2fa";
String VIEW_APPLICATIONS = "view-applications";
String VIEW_CONSENT = "view-consent";
String MANAGE_CONSENT = "manage-consent";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,12 @@ private void setupAccountManagement(RealmModel realm) {
RoleModel manageConsentRole = accountClient.addRole(AccountRoles.MANAGE_CONSENT);
manageConsentRole.setDescription("${role_" + AccountRoles.MANAGE_CONSENT + "}");
manageConsentRole.addCompositeRole(viewConsentRole);
RoleModel manageAccountBasicAuth = accountClient.addRole(AccountRoles.MANAGE_ACCOUNT_BASIC_AUTH);
manageAccountBasicAuth.setDescription("${role_" + AccountRoles.MANAGE_ACCOUNT_BASIC_AUTH + "}");
manageAccount.addCompositeRole(manageAccountBasicAuth);
RoleModel manageAccount2fa = accountClient.addRole(AccountRoles.MANAGE_ACCOUNT_2FA);
manageAccount2fa.setDescription("${role_" + AccountRoles.MANAGE_ACCOUNT_2FA + "}");
manageAccount.addCompositeRole(manageAccount2fa);
RoleModel viewGroups = accountClient.addRole(AccountRoles.VIEW_GROUPS);
viewGroups.setDescription("${role_" + AccountRoles.VIEW_GROUPS + "}");

Expand All @@ -459,7 +465,15 @@ private void setupAccountManagement(RealmModel realm) {

accountConsoleClient.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);

accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.DELETE_ACCOUNT));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.MANAGE_ACCOUNT));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.MANAGE_ACCOUNT_2FA));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.MANAGE_ACCOUNT_BASIC_AUTH));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.MANAGE_ACCOUNT_LINKS));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.MANAGE_CONSENT));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.VIEW_APPLICATIONS));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.VIEW_CONSENT));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.VIEW_PROFILE));
accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.VIEW_GROUPS));

ProtocolMapperModel audienceMapper = new ProtocolMapperModel();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -926,7 +926,7 @@ private Response performAccountLinking(AuthenticationSessionModel authSession, U
return redirectToErrorWhenLinkingFailed(authSession, Messages.IDENTITY_PROVIDER_ALREADY_LINKED, context.getIdpConfig().getAlias());
}

if (!authenticatedUser.hasRole(this.realmModel.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getRole(AccountRoles.MANAGE_ACCOUNT))) {
if (!authenticatedUser.hasRole(this.realmModel.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getRole(AccountRoles.MANAGE_ACCOUNT)) && !authenticatedUser.hasRole(this.realmModel.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getRole(AccountRoles.MANAGE_ACCOUNT_LINKS))) {
return redirectToErrorPage(authSession, Response.Status.FORBIDDEN, Messages.INSUFFICIENT_PERMISSION);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,21 +138,16 @@ public Response getMainPage() throws IOException, FreeMarkerException {

boolean isTotpConfigured = false;
boolean deleteAccountAllowed = false;
boolean isViewGroupsEnabled= false;
if (user != null) {
isTotpConfigured = user.credentialManager().isConfiguredFor(realm.getOTPPolicy().getType());
RoleModel deleteAccountRole = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getRole(AccountRoles.DELETE_ACCOUNT);
deleteAccountAllowed = deleteAccountRole != null && user.hasRole(deleteAccountRole) && realm.getRequiredActionProviderByAlias(DeleteAccount.PROVIDER_ID).isEnabled();
RoleModel viewGrouRole = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getRole(AccountRoles.VIEW_GROUPS);
isViewGroupsEnabled = viewGrouRole != null && user.hasRole(viewGrouRole);


}

map.put("isTotpConfigured", isTotpConfigured);

map.put("deleteAccountAllowed", deleteAccountAllowed);

map.put("isViewGroupsEnabled", isViewGroupsEnabled);

map.put("updateEmailFeatureEnabled", Profile.isFeatureEnabled(Profile.Feature.UPDATE_EMAIL));
RequiredActionProviderModel updateEmailActionProvider = realm.getRequiredActionProviderByAlias(UserModel.RequiredAction.UPDATE_EMAIL.name());
map.put("updateEmailActionEnabled", updateEmailActionProvider != null && updateEmailActionProvider.isEnabled());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ public CredentialTypeMetadata getMetadata() {
@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public Stream<CredentialContainer> credentialTypes(@QueryParam(TYPE) String type,
@QueryParam(USER_CREDENTIALS) Boolean userCredentials) {
auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.VIEW_PROFILE);
auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.VIEW_PROFILE, AccountRoles.MANAGE_ACCOUNT_BASIC_AUTH, AccountRoles.MANAGE_ACCOUNT_2FA);

boolean includeUserCredentials = userCredentials == null || userCredentials;

Expand Down Expand Up @@ -278,7 +278,7 @@ private boolean isFlowEffectivelyDisabled(AuthenticationFlowModel flow) {
@DELETE
@NoCache
public void removeCredential(final @PathParam("credentialId") String credentialId) {
auth.require(AccountRoles.MANAGE_ACCOUNT);
auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT,AccountRoles.MANAGE_ACCOUNT_2FA );
CredentialModel credential = user.credentialManager().getStoredCredentialById(credentialId);
if (credential == null) {
throw new NotFoundException("Credential not found");
Expand All @@ -298,7 +298,7 @@ public void removeCredential(final @PathParam("credentialId") String credentialI
@Path("{credentialId}/label")
@NoCache
public void setLabel(final @PathParam("credentialId") String credentialId, String userLabel) {
auth.require(AccountRoles.MANAGE_ACCOUNT);
auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT,AccountRoles.MANAGE_ACCOUNT_2FA );
CredentialModel credential = user.credentialManager().getStoredCredentialById(credentialId);
if (credential == null) {
throw new NotFoundException("Credential not found");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public LinkedAccountsResource(KeycloakSession session,
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response linkedAccounts() {
auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.VIEW_PROFILE);
auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS, AccountRoles.VIEW_PROFILE);
SortedSet<LinkedAccountRepresentation> linkedAccounts = getLinkedAccounts(this.session, this.realm, this.user);
return Cors.add(request, Response.ok(linkedAccounts)).auth().allowedOrigins(auth.getToken()).build();
}
Expand Down Expand Up @@ -150,7 +150,7 @@ private FederatedIdentityModel getIdentity(Stream<FederatedIdentityModel> identi
@Deprecated
public Response buildLinkedAccountURI(@PathParam("providerId") String providerId,
@QueryParam("redirectUri") String redirectUri) {
auth.require(AccountRoles.MANAGE_ACCOUNT);
auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS);

if (redirectUri == null) {
ErrorResponse.error(Messages.INVALID_REDIRECT_URI, Response.Status.BAD_REQUEST);
Expand Down Expand Up @@ -196,7 +196,7 @@ public Response buildLinkedAccountURI(@PathParam("providerId") String providerId
@Path("/{providerId}")
@Produces(MediaType.APPLICATION_JSON)
public Response removeLinkedAccount(@PathParam("providerId") String providerId) {
auth.require(AccountRoles.MANAGE_ACCOUNT);
auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS);

String errorMessage = checkCommonPreconditions(providerId);
if (errorMessage != null) {
Expand Down Expand Up @@ -227,7 +227,6 @@ public Response removeLinkedAccount(@PathParam("providerId") String providerId)
}

private String checkCommonPreconditions(String providerId) {
auth.require(AccountRoles.MANAGE_ACCOUNT);

if (Validation.isEmpty(providerId)) {
return Messages.MISSING_IDENTITY_PROVIDER;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1431,14 +1431,16 @@ public void applications() {
Assert.assertThat(accountEntry.getRolesAvailable(), containsInAnyOrder(
"Manage account links in Account",
"Manage account in Account",
"Manage basic authentication in Account",
"Manage two factor authentication in Account",
"View profile in Account",
"Offline access"
));
Assert.assertThat(accountEntry.getClientScopesGranted(), containsInAnyOrder("Full Access"));
Assert.assertEquals(oauth.AUTH_SERVER_ROOT + "/realms/test/account/", accountEntry.getHref());

AccountApplicationsPage.AppEntry testAppEntry = apps.get("test-app");
Assert.assertEquals(6, testAppEntry.getRolesAvailable().size());
Assert.assertEquals(8, testAppEntry.getRolesAvailable().size());
Assert.assertTrue(testAppEntry.getRolesAvailable().contains("Offline access"));
Assert.assertTrue(testAppEntry.getClientScopesGranted().contains("Full Access"));
Assert.assertEquals(oauth.APP_AUTH_ROOT, testAppEntry.getHref());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -622,7 +622,7 @@ public void scopes() {
Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAll(), AccountRoles.VIEW_PROFILE);
Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listEffective(), AccountRoles.VIEW_PROFILE);

Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAvailable(), AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS, AccountRoles.VIEW_APPLICATIONS, AccountRoles.VIEW_CONSENT, AccountRoles.MANAGE_CONSENT, AccountRoles.DELETE_ACCOUNT, AccountRoles.VIEW_GROUPS);
Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAvailable(), AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS, AccountRoles.VIEW_APPLICATIONS, AccountRoles.VIEW_CONSENT, AccountRoles.MANAGE_CONSENT, AccountRoles.DELETE_ACCOUNT, AccountRoles.VIEW_GROUPS, AccountRoles.MANAGE_ACCOUNT_BASIC_AUTH, AccountRoles.MANAGE_ACCOUNT_2FA);

Assert.assertNames(scopesResource.getAll().getRealmMappings(), "realm-composite");
Assert.assertNames(scopesResource.getAll().getClientMappings().get(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getMappings(), AccountRoles.VIEW_PROFILE);
Expand All @@ -638,7 +638,7 @@ public void scopes() {
Assert.assertNames(scopesResource.realmLevel().listAvailable(), "offline_access", Constants.AUTHZ_UMA_AUTHORIZATION, "realm-composite", "realm-child", Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + REALM_NAME);
Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAll());

Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAvailable(), AccountRoles.VIEW_PROFILE, AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS, AccountRoles.VIEW_APPLICATIONS, AccountRoles.VIEW_CONSENT, AccountRoles.MANAGE_CONSENT, AccountRoles.DELETE_ACCOUNT, AccountRoles.VIEW_GROUPS);
Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAvailable(), AccountRoles.VIEW_PROFILE, AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS, AccountRoles.VIEW_APPLICATIONS, AccountRoles.VIEW_CONSENT, AccountRoles.MANAGE_CONSENT, AccountRoles.DELETE_ACCOUNT, AccountRoles.VIEW_GROUPS, AccountRoles.MANAGE_ACCOUNT_BASIC_AUTH, AccountRoles.MANAGE_ACCOUNT_2FA);

Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listEffective());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,7 @@
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.keycloak.models.AccountRoles.MANAGE_ACCOUNT;
import static org.keycloak.models.AccountRoles.MANAGE_ACCOUNT_LINKS;
import static org.keycloak.models.AccountRoles.VIEW_GROUPS;
import static org.keycloak.models.AccountRoles.*;
import static org.keycloak.models.Constants.ACCOUNT_MANAGEMENT_CLIENT_ID;
import static org.keycloak.testsuite.Assert.assertNames;
import static org.keycloak.testsuite.auth.page.AuthRealm.MASTER;
Expand Down Expand Up @@ -323,6 +321,8 @@ protected void testMigrationTo19_0_0() {
protected void testMigrationTo20_0_0() {
testViewGroups(masterRealm);
testViewGroups(migrationRealm);
testNewAccountRoles(masterRealm);
testNewAccountRoles(migrationRealm);
}


Expand Down Expand Up @@ -394,8 +394,9 @@ private void testAccountConsoleClient(RealmResource realm) {
MappingsRepresentation scopes = clientResource.getScopeMappings().getAll();
assertNull(scopes.getRealmMappings());
assertEquals(1, scopes.getClientMappings().size());
assertEquals(2, scopes.getClientMappings().get(ACCOUNT_MANAGEMENT_CLIENT_ID).getMappings().size());
Assert.assertNames(scopes.getClientMappings().get(ACCOUNT_MANAGEMENT_CLIENT_ID).getMappings(), MANAGE_ACCOUNT, VIEW_GROUPS);
assertEquals(10, scopes.getClientMappings().get(ACCOUNT_MANAGEMENT_CLIENT_ID).getMappings().size());
Assert.assertNames(scopes.getClientMappings().get(ACCOUNT_MANAGEMENT_CLIENT_ID).getMappings(), DELETE_ACCOUNT, MANAGE_ACCOUNT, MANAGE_ACCOUNT_2FA, MANAGE_ACCOUNT_BASIC_AUTH, MANAGE_ACCOUNT_LINKS, MANAGE_CONSENT, VIEW_APPLICATIONS, VIEW_CONSENT, VIEW_PROFILE, VIEW_GROUPS);

List<ProtocolMapperRepresentation> mappers = clientResource.getProtocolMappers().getMappers();
assertEquals(1, mappers.size());
assertEquals("oidc-audience-resolve-mapper", mappers.get(0).getProtocolMapper());
Expand Down Expand Up @@ -505,6 +506,18 @@ protected void testViewGroups(RealmResource realm) {
assertNotNull(viewAppRole);
}

protected void testNewAccountRoles(RealmResource realm) {
ClientRepresentation accountClient = realm.clients().findByClientId(ACCOUNT_MANAGEMENT_CLIENT_ID).get(0);

ClientResource accountResource = realm.clients().get(accountClient.getId());

RoleRepresentation manageAccountBasicAuth = accountResource.roles().get(AccountRoles.MANAGE_ACCOUNT_BASIC_AUTH).toRepresentation();
assertNotNull(manageAccountBasicAuth);

RoleRepresentation manageAccount2fa = accountResource.roles().get(AccountRoles.MANAGE_ACCOUNT_2FA).toRepresentation();
assertNotNull(manageAccount2fa);
}

protected void testRoleManageAccountLinks(RealmResource... realms) {
log.info("testing role manage account links");
for (RealmResource realm : realms) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,13 @@ private void addTestRealmToTestRealmReps(RealmResource realm) {
public void migration17_xTest() throws Exception{
testMigratedData(false);
testMigrationTo18_x();
testMigrationTo20_x();

// Always test offline-token login during migration test
testOfflineTokenLogin();
testExtremelyLongClientAttribute(migrationRealm);

testMigrationTo20_x();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ public void testUserRolesMovedFromAccessTokenProperties() throws Exception {
// Assert both realm and client roles on the new position. Hardcoded role should be here as well
Map<String, Object> cst1 = (Map<String, Object>) accessToken.getOtherClaims().get("custom");
List<String> roles = (List<String>) cst1.get("roles");
Assert.assertNames(roles, "offline_access", "user", "customer-user", "hardcoded", AccountRoles.VIEW_PROFILE, AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS);
Assert.assertNames(roles, "offline_access", "user", "customer-user", "hardcoded", AccountRoles.VIEW_PROFILE, AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS, AccountRoles.MANAGE_ACCOUNT_BASIC_AUTH, AccountRoles.MANAGE_ACCOUNT_2FA);

// Assert audience
Assert.assertNames(Arrays.asList(accessToken.getAudience()), "account");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ role_manage-events=Manage events
role_view-profile=View profile
role_manage-account=Manage account
role_manage-account-links=Manage account links
role_manage-account-basic-auth=Manage basic authentication
role_manage-account-2fa=Manage two factor authentication
role_manage-consent=Manage consents
role_read-token=Read token
role_offline-access=Offline access
Expand Down
Loading
0