keycloak
静的公開メンバ関数 | 静的公開変数類 | 静的限定公開メンバ関数 | 静的非公開メンバ関数 | 静的非公開変数類 | 全メンバ一覧
org.keycloak.models.utils.RepresentationToModel クラス
org.keycloak.models.utils.RepresentationToModel 連携図
Collaboration graph

静的公開メンバ関数

static OTPPolicy toPolicy (RealmRepresentation rep)
 
static void importRealm (KeycloakSession session, RealmRepresentation rep, RealmModel newRealm, boolean skipUserDependent)
 
static void importUserFederationProvidersAndMappers (KeycloakSession session, RealmRepresentation rep, RealmModel newRealm)
 
static void importRoles (RolesRepresentation realmRoles, RealmModel realm)
 
static void importGroups (RealmModel realm, RealmRepresentation rep)
 
static void importGroup (RealmModel realm, GroupModel parent, GroupRepresentation group)
 
static void importAuthenticationFlows (RealmModel newRealm, RealmRepresentation rep)
 
static void renameRealm (RealmModel realm, String name)
 
static void updateRealm (RealmRepresentation rep, RealmModel realm, KeycloakSession session)
 
static ComponentModel convertFedProviderToComponent (String realmId, UserFederationProviderRepresentation fedModel)
 
static ComponentModel convertFedMapperToComponent (RealmModel realm, ComponentModel parent, UserFederationMapperRepresentation rep, String newMapperType)
 
static void createRole (RealmModel newRealm, RoleRepresentation roleRep)
 
static ClientModel createClient (KeycloakSession session, RealmModel realm, ClientRepresentation resourceRep, boolean addDefaultRoles)
 
static void updateClient (ClientRepresentation rep, ClientModel resource)
 
static ClientScopeModel createClientScope (KeycloakSession session, RealmModel realm, ClientScopeRepresentation resourceRep)
 
static void updateClientScope (ClientScopeRepresentation rep, ClientScopeModel resource)
 
static long getClaimsMask (ClaimRepresentation rep)
 
static void createClientScopeMappings (RealmModel realm, ClientModel clientModel, List< ScopeMappingRepresentation > mappings)
 
static UserModel createUser (KeycloakSession session, RealmModel newRealm, UserRepresentation userRep)
 
static void createCredentials (UserRepresentation userRep, KeycloakSession session, RealmModel realm, UserModel user, boolean adminRequest)
 
static PasswordUserCredentialModel convertCredential (CredentialRepresentation cred)
 
static CredentialModel toModel (CredentialRepresentation cred)
 
static void createRoleMappings (UserRepresentation userRep, UserModel user, RealmModel realm)
 
static void createClientRoleMappings (ClientModel clientModel, UserModel user, List< String > roleNames)
 
static IdentityProviderModel toModel (RealmModel realm, IdentityProviderRepresentation representation)
 
static ProtocolMapperModel toModel (ProtocolMapperRepresentation rep)
 
static IdentityProviderMapperModel toModel (IdentityProviderMapperRepresentation rep)
 
static UserConsentModel toModel (RealmModel newRealm, UserConsentRepresentation consentRep)
 
static AuthenticationFlowModel toModel (AuthenticationFlowRepresentation rep)
 
static AuthenticationExecutionModel toModel (RealmModel realm, AuthenticationExecutionExportRepresentation rep)
 
static AuthenticationExecutionModel toModel (RealmModel realm, AuthenticationExecutionRepresentation rep)
 
static AuthenticatorConfigModel toModel (AuthenticatorConfigRepresentation rep)
 
static RequiredActionProviderModel toModel (RequiredActionProviderRepresentation rep)
 
static ComponentModel toModel (KeycloakSession session, ComponentRepresentation rep)
 
static void updateComponent (KeycloakSession session, ComponentRepresentation rep, ComponentModel component, boolean internal)
 
static void importRealmAuthorizationSettings (RealmRepresentation rep, RealmModel newRealm, KeycloakSession session)
 
static void importAuthorizationSettings (ClientRepresentation clientRepresentation, ClientModel client, KeycloakSession session)
 
static ResourceServer toModel (ResourceServerRepresentation rep, AuthorizationProvider authorization)
 
static Policy toModel (AbstractPolicyRepresentation representation, AuthorizationProvider authorization, Policy model)
 
static Resource toModel (ResourceRepresentation resource, ResourceServer resourceServer, AuthorizationProvider authorization)
 
static Scope toModel (ScopeRepresentation scope, ResourceServer resourceServer, AuthorizationProvider authorization)
 
static PermissionTicket toModel (PermissionTicketRepresentation representation, String resourceServerId, AuthorizationProvider authorization)
 
static void importFederatedUser (KeycloakSession session, RealmModel newRealm, UserRepresentation userRep)
 
static void createFederatedRoleMappings (UserFederatedStorageProvider federatedStorage, UserRepresentation userRep, RealmModel realm)
 
static void createFederatedClientRoleMappings (UserFederatedStorageProvider federatedStorage, RealmModel realm, ClientModel clientModel, UserRepresentation userRep, List< String > roleNames)
 
static ResourceServer createResourceServer (ClientModel client, KeycloakSession session, boolean addDefaultRoles)
 

静的公開変数類

static final String OIDC = "openid-connect"
 

静的限定公開メンバ関数

static void importComponents (RealmModel newRealm, MultivaluedHashMap< String, ComponentExportRepresentation > components, String parentId)
 

静的非公開メンバ関数

static void convertDeprecatedSocialProviders (RealmRepresentation rep)
 
static void convertDeprecatedSocialProviders (UserRepresentation user)
 
static void convertDeprecatedApplications (KeycloakSession session, RealmRepresentation realm)
 
static void convertDeprecatedClientTemplates (RealmRepresentation realm)
 
static String replace (String url, String target, String replacement)
 
static void addComposites (RoleModel role, RoleRepresentation roleRep, RealmModel realm)
 
static Map< String, ClientModelcreateClients (KeycloakSession session, RealmRepresentation rep, RealmModel realm)
 
static void addClientScopeToClient (RealmModel realm, ClientModel client, String clientScopeName, boolean defaultScope)
 
static Map< String, ClientScopeModelcreateClientScopes (KeycloakSession session, List< ClientScopeRepresentation > clientScopes, RealmModel realm)
 
static ScopeContainerModel getScopeContainerHavingScope (RealmModel realm, ScopeMappingRepresentation scope)
 
static void updateCredential (KeycloakSession session, RealmModel realm, UserModel user, CredentialRepresentation cred, boolean adminRequest)
 
static void importIdentityProviders (RealmRepresentation rep, RealmModel newRealm)
 
static void importIdentityProviderMappers (RealmRepresentation rep, RealmModel newRealm)
 
static Policy importPolicies (AuthorizationProvider authorization, ResourceServer resourceServer, List< PolicyRepresentation > policiesToImport, String parentPolicyName)
 
static void updateScopes (Set< String > scopeIds, Policy policy, StoreFactory storeFactory)
 
static void updateAssociatedPolicies (Set< String > policyIds, Policy policy, StoreFactory storeFactory)
 
static void updateResources (Set< String > resourceIds, Policy policy, StoreFactory storeFactory)
 
static Map< String, String > removeEmptyString (Map< String, String > map)
 

静的非公開変数類

static Logger logger = Logger.getLogger(RepresentationToModel.class)
 

詳解

関数詳解

◆ addClientScopeToClient()

static void org.keycloak.models.utils.RepresentationToModel.addClientScopeToClient ( RealmModel  realm,
ClientModel  client,
String  clientScopeName,
boolean  defaultScope 
)
inlinestaticprivate
1257  {
1258  ClientScopeModel clientScope = KeycloakModelUtils.getClientScopeByName(realm, clientScopeName);
1259  if (clientScope != null) {
1260  client.addClientScope(clientScope, defaultScope);
1261  } else {
1262  logger.warnf("Referenced client scope '%s' doesn't exists. Ignoring", clientScopeName);
1263  }
1264  }
static Logger logger
Definition: RepresentationToModel.java:132

◆ addComposites()

static void org.keycloak.models.utils.RepresentationToModel.addComposites ( RoleModel  role,
RoleRepresentation  roleRep,
RealmModel  realm 
)
inlinestaticprivate
1038  {
1039  if (roleRep.getComposites() == null) return;
1040  if (roleRep.getComposites().getRealm() != null) {
1041  for (String roleStr : roleRep.getComposites().getRealm()) {
1042  RoleModel realmRole = realm.getRole(roleStr);
1043  if (realmRole == null) throw new RuntimeException("Unable to find composite realm role: " + roleStr);
1044  role.addCompositeRole(realmRole);
1045  }
1046  }
1047  if (roleRep.getComposites().getClient() != null) {
1048  for (Map.Entry<String, List<String>> entry : roleRep.getComposites().getClient().entrySet()) {
1049  ClientModel client = realm.getClientByClientId(entry.getKey());
1050  if (client == null) {
1051  throw new RuntimeException("App doesn't exist in role definitions: " + roleRep.getName());
1052  }
1053  for (String roleStr : entry.getValue()) {
1054  RoleModel clientRole = client.getRole(roleStr);
1055  if (clientRole == null)
1056  throw new RuntimeException("Unable to find composite client role: " + roleStr);
1057  role.addCompositeRole(clientRole);
1058  }
1059  }
1060 
1061  }
1062 
1063  }

◆ convertCredential()

static PasswordUserCredentialModel org.keycloak.models.utils.RepresentationToModel.convertCredential ( CredentialRepresentation  cred)
inlinestatic
1632  {
1633  PasswordUserCredentialModel credential = new PasswordUserCredentialModel();
1634  credential.setType(cred.getType());
1635  credential.setValue(cred.getValue());
1636  return credential;
1637  }

◆ convertDeprecatedApplications()

static void org.keycloak.models.utils.RepresentationToModel.convertDeprecatedApplications ( KeycloakSession  session,
RealmRepresentation  realm 
)
inlinestaticprivate
729  {
730  if (realm.getApplications() != null || realm.getOauthClients() != null) {
731  if (realm.getClients() == null) {
732  realm.setClients(new LinkedList<ClientRepresentation>());
733  }
734 
735  List<ApplicationRepresentation> clients = new LinkedList<>();
736  if (realm.getApplications() != null) {
737  clients.addAll(realm.getApplications());
738  }
739  if (realm.getOauthClients() != null) {
740  clients.addAll(realm.getOauthClients());
741  }
742 
743  for (ApplicationRepresentation app : clients) {
744  app.setClientId(app.getName());
745  app.setName(null);
746 
747  if (app instanceof OAuthClientRepresentation) {
748  app.setConsentRequired(true);
749  app.setFullScopeAllowed(false);
750  }
751 
752  if (app.getProtocolMappers() == null && app.getClaims() != null) {
753  long mask = getClaimsMask(app.getClaims());
754  List<ProtocolMapperRepresentation> convertedProtocolMappers = session.getProvider(MigrationProvider.class).getMappersForClaimMask(mask);
755  app.setProtocolMappers(convertedProtocolMappers);
756  app.setClaims(null);
757  }
758 
759  realm.getClients().add(app);
760  }
761  }
762 
763  if (realm.getApplicationScopeMappings() != null && realm.getClientScopeMappings() == null) {
764  realm.setClientScopeMappings(realm.getApplicationScopeMappings());
765  }
766 
767  if (realm.getRoles() != null && realm.getRoles().getApplication() != null && realm.getRoles().getClient() == null) {
768  realm.getRoles().setClient(realm.getRoles().getApplication());
769  }
770 
771  if (realm.getUsers() != null) {
772  for (UserRepresentation user : realm.getUsers()) {
773  if (user.getApplicationRoles() != null && user.getClientRoles() == null) {
774  user.setClientRoles(user.getApplicationRoles());
775  }
776  }
777  }
778 
779  if (realm.getRoles() != null && realm.getRoles().getRealm() != null) {
780  for (RoleRepresentation role : realm.getRoles().getRealm()) {
781  if (role.getComposites() != null && role.getComposites().getApplication() != null && role.getComposites().getClient() == null) {
782  role.getComposites().setClient(role.getComposites().getApplication());
783  }
784  }
785  }
786 
787  if (realm.getRoles() != null && realm.getRoles().getClient() != null) {
788  for (Map.Entry<String, List<RoleRepresentation>> clientRoles : realm.getRoles().getClient().entrySet()) {
789  for (RoleRepresentation role : clientRoles.getValue()) {
790  if (role.getComposites() != null && role.getComposites().getApplication() != null && role.getComposites().getClient() == null) {
791  role.getComposites().setClient(role.getComposites().getApplication());
792  }
793  }
794  }
795  }
796  }
static long getClaimsMask(ClaimRepresentation rep)
Definition: RepresentationToModel.java:1399

◆ convertDeprecatedClientTemplates()

static void org.keycloak.models.utils.RepresentationToModel.convertDeprecatedClientTemplates ( RealmRepresentation  realm)
inlinestaticprivate
798  {
799  if (realm.getClientTemplates() != null) {
800 
801  logger.warnf("Using deprecated 'clientTemplates' configuration in JSON representation for realm '%s'. It will be removed in future versions", realm.getRealm());
802 
803  List<ClientScopeRepresentation> clientScopes = new LinkedList<>();
804  for (ClientTemplateRepresentation template : realm.getClientTemplates()) {
805  ClientScopeRepresentation scopeRep = new ClientScopeRepresentation();
806  scopeRep.setId(template.getId());
807  scopeRep.setName(template.getName());
808  scopeRep.setProtocol(template.getProtocol());
809  scopeRep.setDescription(template.getDescription());
810  scopeRep.setAttributes(template.getAttributes());
811  scopeRep.setProtocolMappers(template.getProtocolMappers());
812 
813  clientScopes.add(scopeRep);
814  }
815 
816  realm.setClientScopes(clientScopes);
817  }
818  }
static Logger logger
Definition: RepresentationToModel.java:132

◆ convertDeprecatedSocialProviders() [1/2]

static void org.keycloak.models.utils.RepresentationToModel.convertDeprecatedSocialProviders ( RealmRepresentation  rep)
inlinestaticprivate
678  {
679  if (rep.isSocial() != null && rep.isSocial() && rep.getSocialProviders() != null && !rep.getSocialProviders().isEmpty() && rep.getIdentityProviders() == null) {
680  Boolean updateProfileFirstLogin = rep.isUpdateProfileOnInitialSocialLogin() != null && rep.isUpdateProfileOnInitialSocialLogin();
681  if (rep.getSocialProviders() != null) {
682 
683  logger.warn("Using deprecated 'social' configuration in JSON representation. It will be removed in future versions");
684  List<IdentityProviderRepresentation> identityProviders = new LinkedList<>();
685  for (String k : rep.getSocialProviders().keySet()) {
686  if (k.endsWith(".key")) {
687  String providerId = k.split("\\.")[0];
688  String key = rep.getSocialProviders().get(k);
689  String secret = rep.getSocialProviders().get(k.replace(".key", ".secret"));
690 
691  IdentityProviderRepresentation identityProvider = new IdentityProviderRepresentation();
692  identityProvider.setAlias(providerId);
693  identityProvider.setProviderId(providerId);
694  identityProvider.setEnabled(true);
695  identityProvider.setLinkOnly(false);
696  identityProvider.setUpdateProfileFirstLogin(updateProfileFirstLogin);
697 
698  Map<String, String> config = new HashMap<>();
699  config.put("clientId", key);
700  config.put("clientSecret", secret);
701  identityProvider.setConfig(config);
702 
703  identityProviders.add(identityProvider);
704  }
705  }
706  rep.setIdentityProviders(identityProviders);
707  }
708  }
709  }
static Logger logger
Definition: RepresentationToModel.java:132

◆ convertDeprecatedSocialProviders() [2/2]

static void org.keycloak.models.utils.RepresentationToModel.convertDeprecatedSocialProviders ( UserRepresentation  user)
inlinestaticprivate
711  {
712  if (user.getSocialLinks() != null && !user.getSocialLinks().isEmpty() && user.getFederatedIdentities() == null) {
713 
714  logger.warnf("Using deprecated 'socialLinks' configuration in JSON representation for user '%s'. It will be removed in future versions", user.getUsername());
715  List<FederatedIdentityRepresentation> federatedIdentities = new LinkedList<>();
716  for (SocialLinkRepresentation social : user.getSocialLinks()) {
717  FederatedIdentityRepresentation federatedIdentity = new FederatedIdentityRepresentation();
718  federatedIdentity.setIdentityProvider(social.getSocialProvider());
719  federatedIdentity.setUserId(social.getSocialUserId());
720  federatedIdentity.setUserName(social.getSocialUsername());
721  federatedIdentities.add(federatedIdentity);
722  }
723  user.setFederatedIdentities(federatedIdentities);
724  }
725 
726  user.setSocialLinks(null);
727  }
static Logger logger
Definition: RepresentationToModel.java:132

◆ convertFedMapperToComponent()

static ComponentModel org.keycloak.models.utils.RepresentationToModel.convertFedMapperToComponent ( RealmModel  realm,
ComponentModel  parent,
UserFederationMapperRepresentation  rep,
String  newMapperType 
)
inlinestatic
1015  {
1016  ComponentModel mapper = new ComponentModel();
1017  mapper.setId(rep.getId());
1018  mapper.setName(rep.getName());
1019  mapper.setProviderId(rep.getFederationMapperType());
1020  mapper.setProviderType(newMapperType);
1021  mapper.setParentId(parent.getId());
1022  if (rep.getConfig() != null) {
1023  for (Map.Entry<String, String> entry : rep.getConfig().entrySet()) {
1024  mapper.getConfig().putSingle(entry.getKey(), entry.getValue());
1025  }
1026  }
1027  return mapper;
1028  }

◆ convertFedProviderToComponent()

static ComponentModel org.keycloak.models.utils.RepresentationToModel.convertFedProviderToComponent ( String  realmId,
UserFederationProviderRepresentation  fedModel 
)
inlinestatic
996  {
997  UserStorageProviderModel model = new UserStorageProviderModel();
998  model.setId(fedModel.getId());
999  model.setName(fedModel.getDisplayName());
1000  model.setParentId(realmId);
1001  model.setProviderId(fedModel.getProviderName());
1002  model.setProviderType(UserStorageProvider.class.getName());
1003  model.setFullSyncPeriod(fedModel.getFullSyncPeriod());
1004  model.setPriority(fedModel.getPriority());
1005  model.setChangedSyncPeriod(fedModel.getChangedSyncPeriod());
1006  model.setLastSync(fedModel.getLastSync());
1007  if (fedModel.getConfig() != null) {
1008  for (Map.Entry<String, String> entry : fedModel.getConfig().entrySet()) {
1009  model.getConfig().putSingle(entry.getKey(), entry.getValue());
1010  }
1011  }
1012  return model;
1013  }

◆ createClient()

static ClientModel org.keycloak.models.utils.RepresentationToModel.createClient ( KeycloakSession  session,
RealmModel  realm,
ClientRepresentation  resourceRep,
boolean  addDefaultRoles 
)
inlinestatic

Does not create scope or role mappings!

引数
realm
resourceRep
戻り値
1083  {
1084  logger.debug("Create client: {0}" + resourceRep.getClientId());
1085 
1086  ClientModel client = resourceRep.getId() != null ? realm.addClient(resourceRep.getId(), resourceRep.getClientId()) : realm.addClient(resourceRep.getClientId());
1087  if (resourceRep.getName() != null) client.setName(resourceRep.getName());
1088  if (resourceRep.getDescription() != null) client.setDescription(resourceRep.getDescription());
1089  if (resourceRep.isEnabled() != null) client.setEnabled(resourceRep.isEnabled());
1090  client.setManagementUrl(resourceRep.getAdminUrl());
1091  if (resourceRep.isSurrogateAuthRequired() != null)
1092  client.setSurrogateAuthRequired(resourceRep.isSurrogateAuthRequired());
1093  if (resourceRep.getRootUrl() != null) client.setRootUrl(resourceRep.getRootUrl());
1094  if (resourceRep.getBaseUrl() != null) client.setBaseUrl(resourceRep.getBaseUrl());
1095  if (resourceRep.isBearerOnly() != null) client.setBearerOnly(resourceRep.isBearerOnly());
1096  if (resourceRep.isConsentRequired() != null) client.setConsentRequired(resourceRep.isConsentRequired());
1097 
1098  // Backwards compatibility only
1099  if (resourceRep.isDirectGrantsOnly() != null) {
1100  logger.warn("Using deprecated 'directGrantsOnly' configuration in JSON representation. It will be removed in future versions");
1101  client.setStandardFlowEnabled(!resourceRep.isDirectGrantsOnly());
1102  client.setDirectAccessGrantsEnabled(resourceRep.isDirectGrantsOnly());
1103  }
1104 
1105  if (resourceRep.isStandardFlowEnabled() != null)
1106  client.setStandardFlowEnabled(resourceRep.isStandardFlowEnabled());
1107  if (resourceRep.isImplicitFlowEnabled() != null)
1108  client.setImplicitFlowEnabled(resourceRep.isImplicitFlowEnabled());
1109  if (resourceRep.isDirectAccessGrantsEnabled() != null)
1110  client.setDirectAccessGrantsEnabled(resourceRep.isDirectAccessGrantsEnabled());
1111  if (resourceRep.isServiceAccountsEnabled() != null)
1112  client.setServiceAccountsEnabled(resourceRep.isServiceAccountsEnabled());
1113 
1114  if (resourceRep.isPublicClient() != null) client.setPublicClient(resourceRep.isPublicClient());
1115  if (resourceRep.isFrontchannelLogout() != null)
1116  client.setFrontchannelLogout(resourceRep.isFrontchannelLogout());
1117 
1118  // set defaults to openid-connect if no protocol specified
1119  if (resourceRep.getProtocol() != null) {
1120  client.setProtocol(resourceRep.getProtocol());
1121  } else {
1122  client.setProtocol(OIDC);
1123  }
1124  if (resourceRep.getNodeReRegistrationTimeout() != null) {
1125  client.setNodeReRegistrationTimeout(resourceRep.getNodeReRegistrationTimeout());
1126  } else {
1127  client.setNodeReRegistrationTimeout(-1);
1128  }
1129 
1130  if (resourceRep.getNotBefore() != null) {
1131  client.setNotBefore(resourceRep.getNotBefore());
1132  }
1133 
1134  if (resourceRep.getClientAuthenticatorType() != null) {
1135  client.setClientAuthenticatorType(resourceRep.getClientAuthenticatorType());
1136  } else {
1137  client.setClientAuthenticatorType(KeycloakModelUtils.getDefaultClientAuthenticatorType());
1138  }
1139 
1140  client.setSecret(resourceRep.getSecret());
1141  if (client.getSecret() == null) {
1142  KeycloakModelUtils.generateSecret(client);
1143  }
1144 
1145  if (resourceRep.getAttributes() != null) {
1146  for (Map.Entry<String, String> entry : resourceRep.getAttributes().entrySet()) {
1147  client.setAttribute(entry.getKey(), entry.getValue());
1148  }
1149  }
1150 
1151 
1152  if (resourceRep.getAuthenticationFlowBindingOverrides() != null) {
1153  for (Map.Entry<String, String> entry : resourceRep.getAuthenticationFlowBindingOverrides().entrySet()) {
1154  if (entry.getValue() == null || entry.getValue().trim().equals("")) {
1155  continue;
1156  } else {
1157  String flowId = entry.getValue();
1158  if (client.getRealm().getAuthenticationFlowById(flowId) == null) {
1159  throw new RuntimeException("Unable to resolve auth flow binding override for: " + entry.getKey());
1160  }
1161  client.setAuthenticationFlowBindingOverride(entry.getKey(), entry.getValue());
1162  }
1163  }
1164  }
1165 
1166 
1167  if (resourceRep.getRedirectUris() != null) {
1168  for (String redirectUri : resourceRep.getRedirectUris()) {
1169  client.addRedirectUri(redirectUri);
1170  }
1171  }
1172  if (resourceRep.getWebOrigins() != null) {
1173  for (String webOrigin : resourceRep.getWebOrigins()) {
1174  logger.debugv("Client: {0} webOrigin: {1}", resourceRep.getClientId(), webOrigin);
1175  client.addWebOrigin(webOrigin);
1176  }
1177  } else {
1178  // add origins from redirect uris
1179  if (resourceRep.getRedirectUris() != null) {
1180  Set<String> origins = new HashSet<String>();
1181  for (String redirectUri : resourceRep.getRedirectUris()) {
1182  logger.debugv("add redirect-uri to origin: {0}", redirectUri);
1183  if (redirectUri.startsWith("http")) {
1184  String origin = UriUtils.getOrigin(redirectUri);
1185  logger.debugv("adding default client origin: {0}", origin);
1186  origins.add(origin);
1187  }
1188  }
1189  if (origins.size() > 0) {
1190  client.setWebOrigins(origins);
1191  }
1192  }
1193  }
1194 
1195  if (resourceRep.getRegisteredNodes() != null) {
1196  for (Map.Entry<String, Integer> entry : resourceRep.getRegisteredNodes().entrySet()) {
1197  client.registerNode(entry.getKey(), entry.getValue());
1198  }
1199  }
1200 
1201  if (addDefaultRoles && resourceRep.getDefaultRoles() != null) {
1202  client.updateDefaultRoles(resourceRep.getDefaultRoles());
1203  }
1204 
1205 
1206  if (resourceRep.getProtocolMappers() != null) {
1207  // first, remove all default/built in mappers
1208  Set<ProtocolMapperModel> mappers = client.getProtocolMappers();
1209  for (ProtocolMapperModel mapper : mappers) client.removeProtocolMapper(mapper);
1210 
1211  for (ProtocolMapperRepresentation mapper : resourceRep.getProtocolMappers()) {
1212  client.addProtocolMapper(toModel(mapper));
1213  }
1214 
1215  MigrationUtils.updateProtocolMappers(client);
1216 
1217  }
1218 
1219  if (resourceRep.getClientTemplate() != null) {
1220  String clientTemplateName = KeycloakModelUtils.convertClientScopeName(resourceRep.getClientTemplate());
1221  addClientScopeToClient(realm, client, clientTemplateName, true);
1222  }
1223 
1224  if (resourceRep.getDefaultClientScopes() != null) {
1225  // First remove all default/built in client scopes
1226  for (ClientScopeModel clientScope : client.getClientScopes(true, false).values()) {
1227  client.removeClientScope(clientScope);
1228  }
1229 
1230  for (String clientScopeName : resourceRep.getDefaultClientScopes()) {
1231  addClientScopeToClient(realm, client, clientScopeName, true);
1232  }
1233  }
1234  if (resourceRep.getOptionalClientScopes() != null) {
1235  // First remove all default/built in client scopes
1236  for (ClientScopeModel clientScope : client.getClientScopes(false, false).values()) {
1237  client.removeClientScope(clientScope);
1238  }
1239 
1240  for (String clientScopeName : resourceRep.getOptionalClientScopes()) {
1241  addClientScopeToClient(realm, client, clientScopeName, false);
1242  }
1243  }
1244 
1245  if (resourceRep.isFullScopeAllowed() != null) {
1246  client.setFullScopeAllowed(resourceRep.isFullScopeAllowed());
1247  } else {
1248  client.setFullScopeAllowed(!client.isConsentRequired());
1249  }
1250 
1251  client.updateClient();
1252  resourceRep.setId(client.getId());
1253 
1254  return client;
1255  }
static void addClientScopeToClient(RealmModel realm, ClientModel client, String clientScopeName, boolean defaultScope)
Definition: RepresentationToModel.java:1257
static Logger logger
Definition: RepresentationToModel.java:132
static final String OIDC
Definition: RepresentationToModel.java:133
static CredentialModel toModel(CredentialRepresentation cred)
Definition: RepresentationToModel.java:1639

◆ createClientRoleMappings()

static void org.keycloak.models.utils.RepresentationToModel.createClientRoleMappings ( ClientModel  clientModel,
UserModel  user,
List< String >  roleNames 
)
inlinestatic
1688  {
1689  if (user == null) {
1690  throw new RuntimeException("User not found");
1691  }
1692 
1693  for (String roleName : roleNames) {
1694  RoleModel role = clientModel.getRole(roleName.trim());
1695  if (role == null) {
1696  role = clientModel.addRole(roleName.trim());
1697  }
1698  user.grantRole(role);
1699 
1700  }
1701  }

◆ createClients()

static Map<String, ClientModel> org.keycloak.models.utils.RepresentationToModel.createClients ( KeycloakSession  session,
RealmRepresentation  rep,
RealmModel  realm 
)
inlinestaticprivate
1067  {
1068  Map<String, ClientModel> appMap = new HashMap<String, ClientModel>();
1069  for (ClientRepresentation resourceRep : rep.getClients()) {
1070  ClientModel app = createClient(session, realm, resourceRep, false);
1071  appMap.put(app.getClientId(), app);
1072  }
1073  return appMap;
1074  }
static ClientModel createClient(KeycloakSession session, RealmModel realm, ClientRepresentation resourceRep, boolean addDefaultRoles)
Definition: RepresentationToModel.java:1083

◆ createClientScope()

static ClientScopeModel org.keycloak.models.utils.RepresentationToModel.createClientScope ( KeycloakSession  session,
RealmModel  realm,
ClientScopeRepresentation  resourceRep 
)
inlinestatic
1356  {
1357  logger.debug("Create client scope: {0}" + resourceRep.getName());
1358 
1359  ClientScopeModel clientScope = resourceRep.getId() != null ? realm.addClientScope(resourceRep.getId(), resourceRep.getName()) : realm.addClientScope(resourceRep.getName());
1360  if (resourceRep.getName() != null) clientScope.setName(resourceRep.getName());
1361  if (resourceRep.getDescription() != null) clientScope.setDescription(resourceRep.getDescription());
1362  if (resourceRep.getProtocol() != null) clientScope.setProtocol(resourceRep.getProtocol());
1363  if (resourceRep.getProtocolMappers() != null) {
1364  // first, remove all default/built in mappers
1365  Set<ProtocolMapperModel> mappers = clientScope.getProtocolMappers();
1366  for (ProtocolMapperModel mapper : mappers) clientScope.removeProtocolMapper(mapper);
1367 
1368  for (ProtocolMapperRepresentation mapper : resourceRep.getProtocolMappers()) {
1369  clientScope.addProtocolMapper(toModel(mapper));
1370  }
1371  MigrationUtils.updateProtocolMappers(clientScope);
1372  }
1373 
1374  if (resourceRep.getAttributes() != null) {
1375  for (Map.Entry<String, String> entry : resourceRep.getAttributes().entrySet()) {
1376  clientScope.setAttribute(entry.getKey(), entry.getValue());
1377  }
1378  }
1379 
1380 
1381  return clientScope;
1382  }
static Logger logger
Definition: RepresentationToModel.java:132
static CredentialModel toModel(CredentialRepresentation cred)
Definition: RepresentationToModel.java:1639

◆ createClientScopeMappings()

static void org.keycloak.models.utils.RepresentationToModel.createClientScopeMappings ( RealmModel  realm,
ClientModel  clientModel,
List< ScopeMappingRepresentation mappings 
)
inlinestatic
1457  {
1458  for (ScopeMappingRepresentation mapping : mappings) {
1459  ScopeContainerModel scopeContainer = getScopeContainerHavingScope(realm, mapping);
1460 
1461  for (String roleString : mapping.getRoles()) {
1462  RoleModel role = clientModel.getRole(roleString.trim());
1463  if (role == null) {
1464  role = clientModel.addRole(roleString.trim());
1465  }
1466  scopeContainer.addScopeMapping(role);
1467  }
1468  }
1469  }
static ScopeContainerModel getScopeContainerHavingScope(RealmModel realm, ScopeMappingRepresentation scope)
Definition: RepresentationToModel.java:1471

◆ createClientScopes()

static Map<String, ClientScopeModel> org.keycloak.models.utils.RepresentationToModel.createClientScopes ( KeycloakSession  session,
List< ClientScopeRepresentation clientScopes,
RealmModel  realm 
)
inlinestaticprivate
1347  {
1348  Map<String, ClientScopeModel> appMap = new HashMap<>();
1349  for (ClientScopeRepresentation resourceRep : clientScopes) {
1350  ClientScopeModel app = createClientScope(session, realm, resourceRep);
1351  appMap.put(app.getName(), app);
1352  }
1353  return appMap;
1354  }
static ClientScopeModel createClientScope(KeycloakSession session, RealmModel realm, ClientScopeRepresentation resourceRep)
Definition: RepresentationToModel.java:1356

◆ createCredentials()

static void org.keycloak.models.utils.RepresentationToModel.createCredentials ( UserRepresentation  userRep,
KeycloakSession  session,
RealmModel  realm,
UserModel  user,
boolean  adminRequest 
)
inlinestatic
1564  {
1565  if (userRep.getCredentials() != null) {
1566  for (CredentialRepresentation cred : userRep.getCredentials()) {
1567  updateCredential(session, realm, user, cred, adminRequest);
1568  }
1569  }
1570  }
static void updateCredential(KeycloakSession session, RealmModel realm, UserModel user, CredentialRepresentation cred, boolean adminRequest)
Definition: RepresentationToModel.java:1573

◆ createFederatedClientRoleMappings()

static void org.keycloak.models.utils.RepresentationToModel.createFederatedClientRoleMappings ( UserFederatedStorageProvider  federatedStorage,
RealmModel  realm,
ClientModel  clientModel,
UserRepresentation  userRep,
List< String >  roleNames 
)
inlinestatic
2537  {
2538  if (userRep == null) {
2539  throw new RuntimeException("User not found");
2540  }
2541 
2542  for (String roleName : roleNames) {
2543  RoleModel role = clientModel.getRole(roleName.trim());
2544  if (role == null) {
2545  role = clientModel.addRole(roleName.trim());
2546  }
2547  federatedStorage.grantRole(realm, userRep.getId(), role);
2548 
2549  }
2550  }

◆ createFederatedRoleMappings()

static void org.keycloak.models.utils.RepresentationToModel.createFederatedRoleMappings ( UserFederatedStorageProvider  federatedStorage,
UserRepresentation  userRep,
RealmModel  realm 
)
inlinestatic
2516  {
2517  if (userRep.getRealmRoles() != null) {
2518  for (String roleString : userRep.getRealmRoles()) {
2519  RoleModel role = realm.getRole(roleString.trim());
2520  if (role == null) {
2521  role = realm.addRole(roleString.trim());
2522  }
2523  federatedStorage.grantRole(realm, userRep.getId(), role);
2524  }
2525  }
2526  if (userRep.getClientRoles() != null) {
2527  for (Map.Entry<String, List<String>> entry : userRep.getClientRoles().entrySet()) {
2528  ClientModel client = realm.getClientByClientId(entry.getKey());
2529  if (client == null) {
2530  throw new RuntimeException("Unable to find client role mappings for client: " + entry.getKey());
2531  }
2532  createFederatedClientRoleMappings(federatedStorage, realm, client, userRep, entry.getValue());
2533  }
2534  }
2535  }
static void createFederatedClientRoleMappings(UserFederatedStorageProvider federatedStorage, RealmModel realm, ClientModel clientModel, UserRepresentation userRep, List< String > roleNames)
Definition: RepresentationToModel.java:2537

◆ createResourceServer()

static ResourceServer org.keycloak.models.utils.RepresentationToModel.createResourceServer ( ClientModel  client,
KeycloakSession  session,
boolean  addDefaultRoles 
)
inlinestatic
2567  {
2568  AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
2569  UserModel serviceAccount = session.users().getServiceAccount(client);
2570 
2571  if (serviceAccount == null) {
2572  client.setServiceAccountsEnabled(true);
2573  }
2574 
2575  if (addDefaultRoles) {
2576  RoleModel umaProtectionRole = client.getRole(Constants.AUTHZ_UMA_PROTECTION);
2577 
2578  if (umaProtectionRole == null) {
2579  umaProtectionRole = client.addRole(Constants.AUTHZ_UMA_PROTECTION);
2580  }
2581 
2582  if (serviceAccount != null) {
2583  serviceAccount.grantRole(umaProtectionRole);
2584  }
2585  }
2586 
2587  ResourceServerRepresentation representation = new ResourceServerRepresentation();
2588 
2589  representation.setAllowRemoteResourceManagement(true);
2590  representation.setClientId(client.getId());
2591 
2592  return toModel(representation, authorization);
2593  }
static CredentialModel toModel(CredentialRepresentation cred)
Definition: RepresentationToModel.java:1639

◆ createRole()

static void org.keycloak.models.utils.RepresentationToModel.createRole ( RealmModel  newRealm,
RoleRepresentation  roleRep 
)
inlinestatic
1033  {
1034  RoleModel role = roleRep.getId() != null ? newRealm.addRole(roleRep.getId(), roleRep.getName()) : newRealm.addRole(roleRep.getName());
1035  if (roleRep.getDescription() != null) role.setDescription(roleRep.getDescription());
1036  }

◆ createRoleMappings()

static void org.keycloak.models.utils.RepresentationToModel.createRoleMappings ( UserRepresentation  userRep,
UserModel  user,
RealmModel  realm 
)
inlinestatic
1667  {
1668  if (userRep.getRealmRoles() != null) {
1669  for (String roleString : userRep.getRealmRoles()) {
1670  RoleModel role = realm.getRole(roleString.trim());
1671  if (role == null) {
1672  role = realm.addRole(roleString.trim());
1673  }
1674  user.grantRole(role);
1675  }
1676  }
1677  if (userRep.getClientRoles() != null) {
1678  for (Map.Entry<String, List<String>> entry : userRep.getClientRoles().entrySet()) {
1679  ClientModel client = realm.getClientByClientId(entry.getKey());
1680  if (client == null) {
1681  throw new RuntimeException("Unable to find client role mappings for client: " + entry.getKey());
1682  }
1683  createClientRoleMappings(client, user, entry.getValue());
1684  }
1685  }
1686  }
static void createClientRoleMappings(ClientModel clientModel, UserModel user, List< String > roleNames)
Definition: RepresentationToModel.java:1688

◆ createUser()

static UserModel org.keycloak.models.utils.RepresentationToModel.createUser ( KeycloakSession  session,
RealmModel  newRealm,
UserRepresentation  userRep 
)
inlinestatic
1498  {
1500 
1501  // Import users just to user storage. Don't federate
1502  UserModel user = session.userLocalStorage().addUser(newRealm, userRep.getId(), userRep.getUsername(), false, false);
1503  user.setEnabled(userRep.isEnabled() != null && userRep.isEnabled());
1504  user.setCreatedTimestamp(userRep.getCreatedTimestamp());
1505  user.setEmail(userRep.getEmail());
1506  if (userRep.isEmailVerified() != null) user.setEmailVerified(userRep.isEmailVerified());
1507  user.setFirstName(userRep.getFirstName());
1508  user.setLastName(userRep.getLastName());
1509  user.setFederationLink(userRep.getFederationLink());
1510  if (userRep.getAttributes() != null) {
1511  for (Map.Entry<String, List<String>> entry : userRep.getAttributes().entrySet()) {
1512  List<String> value = entry.getValue();
1513  if (value != null) {
1514  user.setAttribute(entry.getKey(), new ArrayList<>(value));
1515  }
1516  }
1517  }
1518  if (userRep.getRequiredActions() != null) {
1519  for (String requiredAction : userRep.getRequiredActions()) {
1520  user.addRequiredAction(UserModel.RequiredAction.valueOf(requiredAction.toUpperCase()));
1521  }
1522  }
1523  createCredentials(userRep, session, newRealm, user, false);
1524  if (userRep.getFederatedIdentities() != null) {
1525  for (FederatedIdentityRepresentation identity : userRep.getFederatedIdentities()) {
1526  FederatedIdentityModel mappingModel = new FederatedIdentityModel(identity.getIdentityProvider(), identity.getUserId(), identity.getUserName());
1527  session.users().addFederatedIdentity(newRealm, user, mappingModel);
1528  }
1529  }
1530  createRoleMappings(userRep, user, newRealm);
1531  if (userRep.getClientConsents() != null) {
1532  for (UserConsentRepresentation consentRep : userRep.getClientConsents()) {
1533  UserConsentModel consentModel = toModel(newRealm, consentRep);
1534  session.users().addConsent(newRealm, user.getId(), consentModel);
1535  }
1536  }
1537 
1538  if (userRep.getNotBefore() != null) {
1539  session.users().setNotBeforeForUser(newRealm, user, userRep.getNotBefore());
1540  }
1541 
1542  if (userRep.getServiceAccountClientId() != null) {
1543  String clientId = userRep.getServiceAccountClientId();
1544  ClientModel client = newRealm.getClientByClientId(clientId);
1545  if (client == null) {
1546  throw new RuntimeException("Unable to find client specified for service account link. Client: " + clientId);
1547  }
1548  user.setServiceAccountClientLink(client.getId());
1549  ;
1550  }
1551  if (userRep.getGroups() != null) {
1552  for (String path : userRep.getGroups()) {
1553  GroupModel group = KeycloakModelUtils.findGroupByPath(newRealm, path);
1554  if (group == null) {
1555  throw new RuntimeException("Unable to find group specified by path: " + path);
1556 
1557  }
1558  user.joinGroup(group);
1559  }
1560  }
1561  return user;
1562  }
static void createCredentials(UserRepresentation userRep, KeycloakSession session, RealmModel realm, UserModel user, boolean adminRequest)
Definition: RepresentationToModel.java:1564
static void convertDeprecatedSocialProviders(RealmRepresentation rep)
Definition: RepresentationToModel.java:678
static void createRoleMappings(UserRepresentation userRep, UserModel user, RealmModel realm)
Definition: RepresentationToModel.java:1667
static CredentialModel toModel(CredentialRepresentation cred)
Definition: RepresentationToModel.java:1639

◆ getClaimsMask()

static long org.keycloak.models.utils.RepresentationToModel.getClaimsMask ( ClaimRepresentation  rep)
inlinestatic
1399  {
1400  long mask = ClaimMask.ALL;
1401 
1402  if (rep.getAddress()) {
1403  mask |= ClaimMask.ADDRESS;
1404  } else {
1405  mask &= ~ClaimMask.ADDRESS;
1406  }
1407  if (rep.getEmail()) {
1408  mask |= ClaimMask.EMAIL;
1409  } else {
1410  mask &= ~ClaimMask.EMAIL;
1411  }
1412  if (rep.getGender()) {
1413  mask |= ClaimMask.GENDER;
1414  } else {
1415  mask &= ~ClaimMask.GENDER;
1416  }
1417  if (rep.getLocale()) {
1418  mask |= ClaimMask.LOCALE;
1419  } else {
1420  mask &= ~ClaimMask.LOCALE;
1421  }
1422  if (rep.getName()) {
1423  mask |= ClaimMask.NAME;
1424  } else {
1425  mask &= ~ClaimMask.NAME;
1426  }
1427  if (rep.getPhone()) {
1428  mask |= ClaimMask.PHONE;
1429  } else {
1430  mask &= ~ClaimMask.PHONE;
1431  }
1432  if (rep.getPicture()) {
1433  mask |= ClaimMask.PICTURE;
1434  } else {
1435  mask &= ~ClaimMask.PICTURE;
1436  }
1437  if (rep.getProfile()) {
1438  mask |= ClaimMask.PROFILE;
1439  } else {
1440  mask &= ~ClaimMask.PROFILE;
1441  }
1442  if (rep.getUsername()) {
1443  mask |= ClaimMask.USERNAME;
1444  } else {
1445  mask &= ~ClaimMask.USERNAME;
1446  }
1447  if (rep.getWebsite()) {
1448  mask |= ClaimMask.WEBSITE;
1449  } else {
1450  mask &= ~ClaimMask.WEBSITE;
1451  }
1452  return mask;
1453  }

◆ getScopeContainerHavingScope()

static ScopeContainerModel org.keycloak.models.utils.RepresentationToModel.getScopeContainerHavingScope ( RealmModel  realm,
ScopeMappingRepresentation  scope 
)
inlinestaticprivate
1471  {
1472  if (scope.getClient() != null) {
1473  ClientModel client = realm.getClientByClientId(scope.getClient());
1474  if (client == null) {
1475  throw new RuntimeException("Unknown client specification in scope mappings: " + scope.getClient());
1476  }
1477  return client;
1478  } else if (scope.getClientScope() != null) {
1479  ClientScopeModel clientScope = KeycloakModelUtils.getClientScopeByName(realm, scope.getClientScope());
1480  if (clientScope == null) {
1481  throw new RuntimeException("Unknown clientScope specification in scope mappings: " + scope.getClientScope());
1482  }
1483  return clientScope;
1484  } else if (scope.getClientTemplate() != null) { // Backwards compatibility
1485  String templateName = KeycloakModelUtils.convertClientScopeName(scope.getClientTemplate());
1486  ClientScopeModel clientTemplate = KeycloakModelUtils.getClientScopeByName(realm, templateName);
1487  if (clientTemplate == null) {
1488  throw new RuntimeException("Unknown clientScope specification in scope mappings: " + templateName);
1489  }
1490  return clientTemplate;
1491  } else {
1492  throw new RuntimeException("Either client or clientScope needs to be specified in scope mappings");
1493  }
1494  }

◆ importAuthenticationFlows()

static void org.keycloak.models.utils.RepresentationToModel.importAuthenticationFlows ( RealmModel  newRealm,
RealmRepresentation  rep 
)
inlinestatic
585  {
586  if (rep.getAuthenticationFlows() == null) {
587  // assume this is an old version being imported
588  DefaultAuthenticationFlows.migrateFlows(newRealm);
589  } else {
590  for (AuthenticatorConfigRepresentation configRep : rep.getAuthenticatorConfig()) {
591  AuthenticatorConfigModel model = toModel(configRep);
592  newRealm.addAuthenticatorConfig(model);
593  }
594  for (AuthenticationFlowRepresentation flowRep : rep.getAuthenticationFlows()) {
595  AuthenticationFlowModel model = toModel(flowRep);
596  // make sure new id is generated for new AuthenticationFlowModel instance
597  model.setId(null);
598  model = newRealm.addAuthenticationFlow(model);
599  }
600  for (AuthenticationFlowRepresentation flowRep : rep.getAuthenticationFlows()) {
601  AuthenticationFlowModel model = newRealm.getFlowByAlias(flowRep.getAlias());
602  for (AuthenticationExecutionExportRepresentation exeRep : flowRep.getAuthenticationExecutions()) {
603  AuthenticationExecutionModel execution = toModel(newRealm, exeRep);
604  execution.setParentFlow(model.getId());
605  newRealm.addAuthenticatorExecution(execution);
606  }
607  }
608  }
609  if (rep.getBrowserFlow() == null) {
610  newRealm.setBrowserFlow(newRealm.getFlowByAlias(DefaultAuthenticationFlows.BROWSER_FLOW));
611  } else {
612  newRealm.setBrowserFlow(newRealm.getFlowByAlias(rep.getBrowserFlow()));
613  }
614  if (rep.getRegistrationFlow() == null) {
615  newRealm.setRegistrationFlow(newRealm.getFlowByAlias(DefaultAuthenticationFlows.REGISTRATION_FLOW));
616  } else {
617  newRealm.setRegistrationFlow(newRealm.getFlowByAlias(rep.getRegistrationFlow()));
618  }
619  if (rep.getDirectGrantFlow() == null) {
620  newRealm.setDirectGrantFlow(newRealm.getFlowByAlias(DefaultAuthenticationFlows.DIRECT_GRANT_FLOW));
621  } else {
622  newRealm.setDirectGrantFlow(newRealm.getFlowByAlias(rep.getDirectGrantFlow()));
623  }
624 
625  // reset credentials + client flow needs to be more defensive as they were added later (in 1.5 )
626  if (rep.getResetCredentialsFlow() == null) {
627  AuthenticationFlowModel resetFlow = newRealm.getFlowByAlias(DefaultAuthenticationFlows.RESET_CREDENTIALS_FLOW);
628  if (resetFlow == null) {
629  DefaultAuthenticationFlows.resetCredentialsFlow(newRealm);
630  } else {
631  newRealm.setResetCredentialsFlow(resetFlow);
632  }
633  } else {
634  newRealm.setResetCredentialsFlow(newRealm.getFlowByAlias(rep.getResetCredentialsFlow()));
635  }
636  if (rep.getClientAuthenticationFlow() == null) {
637  AuthenticationFlowModel clientFlow = newRealm.getFlowByAlias(DefaultAuthenticationFlows.CLIENT_AUTHENTICATION_FLOW);
638  if (clientFlow == null) {
639  DefaultAuthenticationFlows.clientAuthFlow(newRealm);
640  } else {
641  newRealm.setClientAuthenticationFlow(clientFlow);
642  }
643  } else {
644  newRealm.setClientAuthenticationFlow(newRealm.getFlowByAlias(rep.getClientAuthenticationFlow()));
645  }
646 
647  // Added in 1.7
648  if (newRealm.getFlowByAlias(DefaultAuthenticationFlows.FIRST_BROKER_LOGIN_FLOW) == null) {
649  DefaultAuthenticationFlows.firstBrokerLoginFlow(newRealm, true);
650  }
651 
652  // Added in 2.2
653  String defaultProvider = null;
654  if (rep.getIdentityProviders() != null) {
655  for (IdentityProviderRepresentation i : rep.getIdentityProviders()) {
656  if (i.isEnabled() && i.isAuthenticateByDefault()) {
657  defaultProvider = i.getProviderId();
658  break;
659  }
660  }
661  }
662 
663  // Added in 3.2
664  if (rep.getDockerAuthenticationFlow() == null) {
665  AuthenticationFlowModel dockerAuthenticationFlow = newRealm.getFlowByAlias(DefaultAuthenticationFlows.DOCKER_AUTH);
666  if (dockerAuthenticationFlow == null) {
667  DefaultAuthenticationFlows.dockerAuthenticationFlow(newRealm);
668  } else {
669  newRealm.setDockerAuthenticationFlow(dockerAuthenticationFlow);
670  }
671  } else {
672  newRealm.setDockerAuthenticationFlow(newRealm.getFlowByAlias(rep.getDockerAuthenticationFlow()));
673  }
674 
675  DefaultAuthenticationFlows.addIdentityProviderAuthenticator(newRealm, defaultProvider);
676  }
static CredentialModel toModel(CredentialRepresentation cred)
Definition: RepresentationToModel.java:1639

◆ importAuthorizationSettings()

static void org.keycloak.models.utils.RepresentationToModel.importAuthorizationSettings ( ClientRepresentation  clientRepresentation,
ClientModel  client,
KeycloakSession  session 
)
inlinestatic
1974  {
1975  if (Boolean.TRUE.equals(clientRepresentation.getAuthorizationServicesEnabled())) {
1976  AuthorizationProviderFactory authorizationFactory = (AuthorizationProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(AuthorizationProvider.class);
1977  AuthorizationProvider authorization = authorizationFactory.create(session, client.getRealm());
1978 
1979  client.setServiceAccountsEnabled(true);
1980  client.setBearerOnly(false);
1981  client.setPublicClient(false);
1982 
1983  ResourceServerRepresentation rep = clientRepresentation.getAuthorizationSettings();
1984 
1985  if (rep == null) {
1986  rep = new ResourceServerRepresentation();
1987  }
1988 
1989  rep.setClientId(client.getId());
1990 
1991  toModel(rep, authorization);
1992  }
1993  }
static CredentialModel toModel(CredentialRepresentation cred)
Definition: RepresentationToModel.java:1639

◆ importComponents()

static void org.keycloak.models.utils.RepresentationToModel.importComponents ( RealmModel  newRealm,
MultivaluedHashMap< String, ComponentExportRepresentation components,
String  parentId 
)
inlinestaticprotected
471  {
472  for (Map.Entry<String, List<ComponentExportRepresentation>> entry : components.entrySet()) {
473  String providerType = entry.getKey();
474  for (ComponentExportRepresentation compRep : entry.getValue()) {
475  ComponentModel component = new ComponentModel();
476  component.setId(compRep.getId());
477  component.setName(compRep.getName());
478  component.setConfig(compRep.getConfig());
479  component.setProviderType(providerType);
480  component.setProviderId(compRep.getProviderId());
481  component.setSubType(compRep.getSubType());
482  component.setParentId(parentId);
483  component = newRealm.importComponentModel(component);
484  if (compRep.getSubComponents() != null) {
485  importComponents(newRealm, compRep.getSubComponents(), component.getId());
486  }
487  }
488  }
489  }
static void importComponents(RealmModel newRealm, MultivaluedHashMap< String, ComponentExportRepresentation > components, String parentId)
Definition: RepresentationToModel.java:471

◆ importFederatedUser()

static void org.keycloak.models.utils.RepresentationToModel.importFederatedUser ( KeycloakSession  session,
RealmModel  newRealm,
UserRepresentation  userRep 
)
inlinestatic
2463  {
2464  UserFederatedStorageProvider federatedStorage = session.userFederatedStorage();
2465  if (userRep.getAttributes() != null) {
2466  for (Map.Entry<String, List<String>> entry : userRep.getAttributes().entrySet()) {
2467  String key = entry.getKey();
2468  List<String> value = entry.getValue();
2469  if (value != null) {
2470  federatedStorage.setAttribute(newRealm, userRep.getId(), key, new LinkedList<>(value));
2471  }
2472  }
2473  }
2474  if (userRep.getRequiredActions() != null) {
2475  for (String action : userRep.getRequiredActions()) {
2476  federatedStorage.addRequiredAction(newRealm, userRep.getId(), action);
2477  }
2478  }
2479  if (userRep.getCredentials() != null) {
2480  for (CredentialRepresentation cred : userRep.getCredentials()) {
2481  federatedStorage.createCredential(newRealm, userRep.getId(), toModel(cred));
2482  }
2483  }
2484  createFederatedRoleMappings(federatedStorage, userRep, newRealm);
2485 
2486  if (userRep.getGroups() != null) {
2487  for (String path : userRep.getGroups()) {
2488  GroupModel group = KeycloakModelUtils.findGroupByPath(newRealm, path);
2489  if (group == null) {
2490  throw new RuntimeException("Unable to find group specified by path: " + path);
2491 
2492  }
2493  federatedStorage.joinGroup(newRealm, userRep.getId(), group);
2494  }
2495  }
2496 
2497  if (userRep.getFederatedIdentities() != null) {
2498  for (FederatedIdentityRepresentation identity : userRep.getFederatedIdentities()) {
2499  FederatedIdentityModel mappingModel = new FederatedIdentityModel(identity.getIdentityProvider(), identity.getUserId(), identity.getUserName());
2500  federatedStorage.addFederatedIdentity(newRealm, userRep.getId(), mappingModel);
2501  }
2502  }
2503  if (userRep.getClientConsents() != null) {
2504  for (UserConsentRepresentation consentRep : userRep.getClientConsents()) {
2505  UserConsentModel consentModel = toModel(newRealm, consentRep);
2506  federatedStorage.addConsent(newRealm, userRep.getId(), consentModel);
2507  }
2508  }
2509  if (userRep.getNotBefore() != null) {
2510  federatedStorage.setNotBeforeForUser(newRealm, userRep.getId(), userRep.getNotBefore());
2511  }
2512 
2513 
2514  }
static void createFederatedRoleMappings(UserFederatedStorageProvider federatedStorage, UserRepresentation userRep, RealmModel realm)
Definition: RepresentationToModel.java:2516
static CredentialModel toModel(CredentialRepresentation cred)
Definition: RepresentationToModel.java:1639

◆ importGroup()

static void org.keycloak.models.utils.RepresentationToModel.importGroup ( RealmModel  realm,
GroupModel  parent,
GroupRepresentation  group 
)
inlinestatic
543  {
544  GroupModel newGroup = realm.createGroup(group.getId(), group.getName());
545  if (group.getAttributes() != null) {
546  for (Map.Entry<String, List<String>> attr : group.getAttributes().entrySet()) {
547  newGroup.setAttribute(attr.getKey(), attr.getValue());
548  }
549  }
550  realm.moveGroup(newGroup, parent);
551 
552  if (group.getRealmRoles() != null) {
553  for (String roleString : group.getRealmRoles()) {
554  RoleModel role = realm.getRole(roleString.trim());
555  if (role == null) {
556  role = realm.addRole(roleString.trim());
557  }
558  newGroup.grantRole(role);
559  }
560  }
561  if (group.getClientRoles() != null) {
562  for (Map.Entry<String, List<String>> entry : group.getClientRoles().entrySet()) {
563  ClientModel client = realm.getClientByClientId(entry.getKey());
564  if (client == null) {
565  throw new RuntimeException("Unable to find client role mappings for client: " + entry.getKey());
566  }
567  List<String> roleNames = entry.getValue();
568  for (String roleName : roleNames) {
569  RoleModel role = client.getRole(roleName.trim());
570  if (role == null) {
571  role = client.addRole(roleName.trim());
572  }
573  newGroup.grantRole(role);
574 
575  }
576  }
577  }
578  if (group.getSubGroups() != null) {
579  for (GroupRepresentation subGroup : group.getSubGroups()) {
580  importGroup(realm, newGroup, subGroup);
581  }
582  }
583  }
static void importGroup(RealmModel realm, GroupModel parent, GroupRepresentation group)
Definition: RepresentationToModel.java:543

◆ importGroups()

static void org.keycloak.models.utils.RepresentationToModel.importGroups ( RealmModel  realm,
RealmRepresentation  rep 
)
inlinestatic
533  {
534  List<GroupRepresentation> groups = rep.getGroups();
535  if (groups == null) return;
536 
537  GroupModel parent = null;
538  for (GroupRepresentation group : groups) {
539  importGroup(realm, parent, group);
540  }
541  }
static void importGroup(RealmModel realm, GroupModel parent, GroupRepresentation group)
Definition: RepresentationToModel.java:543

◆ importIdentityProviderMappers()

static void org.keycloak.models.utils.RepresentationToModel.importIdentityProviderMappers ( RealmRepresentation  rep,
RealmModel  newRealm 
)
inlinestaticprivate
1711  {
1712  if (rep.getIdentityProviderMappers() != null) {
1713  for (IdentityProviderMapperRepresentation representation : rep.getIdentityProviderMappers()) {
1714  newRealm.addIdentityProviderMapper(toModel(representation));
1715  }
1716  }
1717  }
static CredentialModel toModel(CredentialRepresentation cred)
Definition: RepresentationToModel.java:1639

◆ importIdentityProviders()

static void org.keycloak.models.utils.RepresentationToModel.importIdentityProviders ( RealmRepresentation  rep,
RealmModel  newRealm 
)
inlinestaticprivate
1703  {
1704  if (rep.getIdentityProviders() != null) {
1705  for (IdentityProviderRepresentation representation : rep.getIdentityProviders()) {
1706  newRealm.addIdentityProvider(toModel(newRealm, representation));
1707  }
1708  }
1709  }
static CredentialModel toModel(CredentialRepresentation cred)
Definition: RepresentationToModel.java:1639

◆ importPolicies()

static Policy org.keycloak.models.utils.RepresentationToModel.importPolicies ( AuthorizationProvider  authorization,
ResourceServer  resourceServer,
List< PolicyRepresentation policiesToImport,
String  parentPolicyName 
)
inlinestaticprivate
2041  {
2042  StoreFactory storeFactory = authorization.getStoreFactory();
2043  for (PolicyRepresentation policyRepresentation : policiesToImport) {
2044  if (parentPolicyName != null && !parentPolicyName.equals(policyRepresentation.getName())) {
2045  continue;
2046  }
2047 
2048  Map<String, String> config = policyRepresentation.getConfig();
2049  String applyPolicies = config.get("applyPolicies");
2050 
2051  if (applyPolicies != null && !applyPolicies.isEmpty()) {
2052  PolicyStore policyStore = storeFactory.getPolicyStore();
2053  try {
2054  List<String> policies = (List<String>) JsonSerialization.readValue(applyPolicies, List.class);
2055  Set<String> policyIds = new HashSet<>();
2056 
2057  for (String policyName : policies) {
2058  Policy policy = policyStore.findByName(policyName, resourceServer.getId());
2059 
2060  if (policy == null) {
2061  policy = policyStore.findById(policyName, resourceServer.getId());
2062  }
2063 
2064  if (policy == null) {
2065  policy = importPolicies(authorization, resourceServer, policiesToImport, policyName);
2066  if (policy == null) {
2067  throw new RuntimeException("Policy with name [" + policyName + "] not defined.");
2068  }
2069  }
2070 
2071  policyIds.add(policy.getId());
2072  }
2073 
2074  config.put("applyPolicies", JsonSerialization.writeValueAsString(policyIds));
2075  } catch (Exception e) {
2076  throw new RuntimeException("Error while importing policy [" + policyRepresentation.getName() + "].", e);
2077  }
2078  }
2079 
2080  PolicyStore policyStore = storeFactory.getPolicyStore();
2081  Policy policy = policyStore.findById(policyRepresentation.getId(), resourceServer.getId());
2082 
2083  if (policy == null) {
2084  policy = policyStore.findByName(policyRepresentation.getName(), resourceServer.getId());
2085  }
2086 
2087  if (policy == null) {
2088  policy = policyStore.create(policyRepresentation, resourceServer);
2089  } else {
2090  policy = toModel(policyRepresentation, authorization, policy);
2091  }
2092 
2093  if (parentPolicyName != null && parentPolicyName.equals(policyRepresentation.getName())) {
2094  return policy;
2095  }
2096  }
2097 
2098  return null;
2099  }
static Policy importPolicies(AuthorizationProvider authorization, ResourceServer resourceServer, List< PolicyRepresentation > policiesToImport, String parentPolicyName)
Definition: RepresentationToModel.java:2041
static CredentialModel toModel(CredentialRepresentation cred)
Definition: RepresentationToModel.java:1639

◆ importRealm()

static void org.keycloak.models.utils.RepresentationToModel.importRealm ( KeycloakSession  session,
RealmRepresentation  rep,
RealmModel  newRealm,
boolean  skipUserDependent 
)
inlinestatic
147  {
149  convertDeprecatedApplications(session, rep);
151 
152  newRealm.setName(rep.getRealm());
153  if (rep.getDisplayName() != null) newRealm.setDisplayName(rep.getDisplayName());
154  if (rep.getDisplayNameHtml() != null) newRealm.setDisplayNameHtml(rep.getDisplayNameHtml());
155  if (rep.isEnabled() != null) newRealm.setEnabled(rep.isEnabled());
156  if (rep.isUserManagedAccessAllowed() != null) newRealm.setUserManagedAccessAllowed(rep.isUserManagedAccessAllowed());
157  if (rep.isBruteForceProtected() != null) newRealm.setBruteForceProtected(rep.isBruteForceProtected());
158  if (rep.isPermanentLockout() != null) newRealm.setPermanentLockout(rep.isPermanentLockout());
159  if (rep.getMaxFailureWaitSeconds() != null) newRealm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds());
160  if (rep.getMinimumQuickLoginWaitSeconds() != null)
161  newRealm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds());
162  if (rep.getWaitIncrementSeconds() != null) newRealm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds());
163  if (rep.getQuickLoginCheckMilliSeconds() != null)
164  newRealm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds());
165  if (rep.getMaxDeltaTimeSeconds() != null) newRealm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds());
166  if (rep.getFailureFactor() != null) newRealm.setFailureFactor(rep.getFailureFactor());
167  if (rep.isEventsEnabled() != null) newRealm.setEventsEnabled(rep.isEventsEnabled());
168  if (rep.getEnabledEventTypes() != null)
169  newRealm.setEnabledEventTypes(new HashSet<>(rep.getEnabledEventTypes()));
170  if (rep.getEventsExpiration() != null) newRealm.setEventsExpiration(rep.getEventsExpiration());
171  if (rep.getEventsListeners() != null) newRealm.setEventsListeners(new HashSet<>(rep.getEventsListeners()));
172  if (rep.isAdminEventsEnabled() != null) newRealm.setAdminEventsEnabled(rep.isAdminEventsEnabled());
173  if (rep.isAdminEventsDetailsEnabled() != null)
174  newRealm.setAdminEventsDetailsEnabled(rep.isAdminEventsDetailsEnabled());
175 
176  if (rep.getNotBefore() != null) newRealm.setNotBefore(rep.getNotBefore());
177 
178  if (rep.getDefaultSignatureAlgorithm() != null) newRealm.setDefaultSignatureAlgorithm(rep.getDefaultSignatureAlgorithm());
179 
180  if (rep.getRevokeRefreshToken() != null) newRealm.setRevokeRefreshToken(rep.getRevokeRefreshToken());
181  else newRealm.setRevokeRefreshToken(false);
182 
183  if (rep.getRefreshTokenMaxReuse() != null) newRealm.setRefreshTokenMaxReuse(rep.getRefreshTokenMaxReuse());
184  else newRealm.setRefreshTokenMaxReuse(0);
185 
186  if (rep.getAccessTokenLifespan() != null) newRealm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
187  else newRealm.setAccessTokenLifespan(300);
188 
189  if (rep.getAccessTokenLifespanForImplicitFlow() != null)
190  newRealm.setAccessTokenLifespanForImplicitFlow(rep.getAccessTokenLifespanForImplicitFlow());
191  else
192  newRealm.setAccessTokenLifespanForImplicitFlow(Constants.DEFAULT_ACCESS_TOKEN_LIFESPAN_FOR_IMPLICIT_FLOW_TIMEOUT);
193 
194  if (rep.getSsoSessionIdleTimeout() != null) newRealm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout());
195  else newRealm.setSsoSessionIdleTimeout(1800);
196  if (rep.getSsoSessionMaxLifespan() != null) newRealm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan());
197  else newRealm.setSsoSessionMaxLifespan(36000);
198  if (rep.getOfflineSessionIdleTimeout() != null)
199  newRealm.setOfflineSessionIdleTimeout(rep.getOfflineSessionIdleTimeout());
200  else newRealm.setOfflineSessionIdleTimeout(Constants.DEFAULT_OFFLINE_SESSION_IDLE_TIMEOUT);
201 
202  // KEYCLOAK-7688 Offline Session Max for Offline Token
203  if (rep.getOfflineSessionMaxLifespanEnabled() != null) newRealm.setOfflineSessionMaxLifespanEnabled(rep.getOfflineSessionMaxLifespanEnabled());
204  else newRealm.setOfflineSessionMaxLifespanEnabled(false);
205 
206  if (rep.getOfflineSessionMaxLifespan() != null)
207  newRealm.setOfflineSessionMaxLifespan(rep.getOfflineSessionMaxLifespan());
208  else newRealm.setOfflineSessionMaxLifespan(Constants.DEFAULT_OFFLINE_SESSION_MAX_LIFESPAN);
209 
210  if (rep.getAccessCodeLifespan() != null) newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
211  else newRealm.setAccessCodeLifespan(60);
212 
213  if (rep.getAccessCodeLifespanUserAction() != null)
214  newRealm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction());
215  else newRealm.setAccessCodeLifespanUserAction(300);
216 
217  if (rep.getAccessCodeLifespanLogin() != null)
218  newRealm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin());
219  else newRealm.setAccessCodeLifespanLogin(1800);
220 
221  if (rep.getActionTokenGeneratedByAdminLifespan() != null)
222  newRealm.setActionTokenGeneratedByAdminLifespan(rep.getActionTokenGeneratedByAdminLifespan());
223  else newRealm.setActionTokenGeneratedByAdminLifespan(12 * 60 * 60);
224 
225  if (rep.getActionTokenGeneratedByUserLifespan() != null)
226  newRealm.setActionTokenGeneratedByUserLifespan(rep.getActionTokenGeneratedByUserLifespan());
227  else newRealm.setActionTokenGeneratedByUserLifespan(newRealm.getAccessCodeLifespanUserAction());
228 
229  if (rep.getSslRequired() != null)
230  newRealm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase()));
231  if (rep.isRegistrationAllowed() != null) newRealm.setRegistrationAllowed(rep.isRegistrationAllowed());
232  if (rep.isRegistrationEmailAsUsername() != null)
233  newRealm.setRegistrationEmailAsUsername(rep.isRegistrationEmailAsUsername());
234  if (rep.isRememberMe() != null) newRealm.setRememberMe(rep.isRememberMe());
235  if (rep.isVerifyEmail() != null) newRealm.setVerifyEmail(rep.isVerifyEmail());
236  if (rep.isLoginWithEmailAllowed() != null) newRealm.setLoginWithEmailAllowed(rep.isLoginWithEmailAllowed());
237  if (rep.isDuplicateEmailsAllowed() != null) newRealm.setDuplicateEmailsAllowed(rep.isDuplicateEmailsAllowed());
238  if (rep.isResetPasswordAllowed() != null) newRealm.setResetPasswordAllowed(rep.isResetPasswordAllowed());
239  if (rep.isEditUsernameAllowed() != null) newRealm.setEditUsernameAllowed(rep.isEditUsernameAllowed());
240  if (rep.getLoginTheme() != null) newRealm.setLoginTheme(rep.getLoginTheme());
241  if (rep.getAccountTheme() != null) newRealm.setAccountTheme(rep.getAccountTheme());
242  if (rep.getAdminTheme() != null) newRealm.setAdminTheme(rep.getAdminTheme());
243  if (rep.getEmailTheme() != null) newRealm.setEmailTheme(rep.getEmailTheme());
244 
245  // todo remove this stuff as its all deprecated
246  if (rep.getRequiredCredentials() != null) {
247  for (String requiredCred : rep.getRequiredCredentials()) {
248  newRealm.addRequiredCredential(requiredCred);
249  }
250  } else {
251  newRealm.addRequiredCredential(CredentialRepresentation.PASSWORD);
252  }
253 
254  if (rep.getPasswordPolicy() != null)
255  newRealm.setPasswordPolicy(PasswordPolicy.parse(session, rep.getPasswordPolicy()));
256  if (rep.getOtpPolicyType() != null) newRealm.setOTPPolicy(toPolicy(rep));
257  else newRealm.setOTPPolicy(OTPPolicy.DEFAULT_POLICY);
258 
259  importAuthenticationFlows(newRealm, rep);
260  if (rep.getRequiredActions() != null) {
261  for (RequiredActionProviderRepresentation action : rep.getRequiredActions()) {
262  RequiredActionProviderModel model = toModel(action);
263 
264  MigrationUtils.updateOTPRequiredAction(model);
265 
266  newRealm.addRequiredActionProvider(model);
267  }
268  } else {
269  DefaultRequiredActions.addActions(newRealm);
270  }
271 
272  importIdentityProviders(rep, newRealm);
273  importIdentityProviderMappers(rep, newRealm);
274 
275  Map<String, ClientScopeModel> clientScopes = new HashMap<>();
276  if (rep.getClientScopes() != null) {
277  clientScopes = createClientScopes(session, rep.getClientScopes(), newRealm);
278  }
279  if (rep.getDefaultDefaultClientScopes() != null) {
280  for (String clientScopeName : rep.getDefaultDefaultClientScopes()) {
281  ClientScopeModel clientScope = clientScopes.get(clientScopeName);
282  if (clientScope != null) {
283  newRealm.addDefaultClientScope(clientScope, true);
284  } else {
285  logger.warnf("Referenced client scope '%s' doesn't exists", clientScopeName);
286  }
287  }
288  }
289  if (rep.getDefaultOptionalClientScopes() != null) {
290  for (String clientScopeName : rep.getDefaultOptionalClientScopes()) {
291  ClientScopeModel clientScope = clientScopes.get(clientScopeName);
292  if (clientScope != null) {
293  newRealm.addDefaultClientScope(clientScope, false);
294  } else {
295  logger.warnf("Referenced client scope '%s' doesn't exists", clientScopeName);
296  }
297  }
298  }
299 
300  if (rep.getClients() != null) {
301  createClients(session, rep, newRealm);
302  }
303 
304  importRoles(rep.getRoles(), newRealm);
305 
306  // Setup realm default roles
307  if (rep.getDefaultRoles() != null) {
308  for (String roleString : rep.getDefaultRoles()) {
309  newRealm.addDefaultRole(roleString.trim());
310  }
311  }
312  // Setup client default roles
313  if (rep.getClients() != null) {
314  for (ClientRepresentation resourceRep : rep.getClients()) {
315  if (resourceRep.getDefaultRoles() != null) {
316  ClientModel clientModel = newRealm.getClientByClientId(resourceRep.getClientId());
317  clientModel.updateDefaultRoles(resourceRep.getDefaultRoles());
318  }
319  }
320  }
321 
322  // Now that all possible roles and clients are created, create scope mappings
323 
324  //Map<String, ClientModel> appMap = newRealm.getClientNameMap();
325 
326  if (rep.getClientScopeMappings() != null) {
327 
328  for (Map.Entry<String, List<ScopeMappingRepresentation>> entry : rep.getClientScopeMappings().entrySet()) {
329  ClientModel app = newRealm.getClientByClientId(entry.getKey());
330  if (app == null) {
331  throw new RuntimeException("Unable to find client role mappings for client: " + entry.getKey());
332  }
333  createClientScopeMappings(newRealm, app, entry.getValue());
334  }
335  }
336 
337  if (rep.getScopeMappings() != null) {
338  for (ScopeMappingRepresentation scope : rep.getScopeMappings()) {
339  ScopeContainerModel scopeContainer = getScopeContainerHavingScope(newRealm, scope);
340 
341  for (String roleString : scope.getRoles()) {
342  RoleModel role = newRealm.getRole(roleString.trim());
343  if (role == null) {
344  role = newRealm.addRole(roleString.trim());
345  }
346  scopeContainer.addScopeMapping(role);
347  }
348 
349  }
350  }
351 
352  if (rep.getSmtpServer() != null) {
353  newRealm.setSmtpConfig(new HashMap(rep.getSmtpServer()));
354  }
355 
356  if (rep.getBrowserSecurityHeaders() != null) {
357  newRealm.setBrowserSecurityHeaders(rep.getBrowserSecurityHeaders());
358  } else {
359  newRealm.setBrowserSecurityHeaders(BrowserSecurityHeaders.defaultHeaders);
360  }
361 
362  if (rep.getComponents() != null) {
363  MultivaluedHashMap<String, ComponentExportRepresentation> components = rep.getComponents();
364  String parentId = newRealm.getId();
365  importComponents(newRealm, components, parentId);
366  }
367  importUserFederationProvidersAndMappers(session, rep, newRealm);
368 
369 
370  if (rep.getGroups() != null) {
371  importGroups(newRealm, rep);
372  if (rep.getDefaultGroups() != null) {
373  for (String path : rep.getDefaultGroups()) {
374  GroupModel found = KeycloakModelUtils.findGroupByPath(newRealm, path);
375  if (found == null) throw new RuntimeException("default group in realm rep doesn't exist: " + path);
376  newRealm.addDefaultGroup(found);
377  }
378  }
379  }
380 
381 
382  // create users and their role mappings and social mappings
383 
384  if (rep.getUsers() != null) {
385  for (UserRepresentation userRep : rep.getUsers()) {
386  UserModel user = createUser(session, newRealm, userRep);
387  }
388  }
389 
390  if (rep.getFederatedUsers() != null) {
391  for (UserRepresentation userRep : rep.getFederatedUsers()) {
392  importFederatedUser(session, newRealm, userRep);
393 
394  }
395  }
396 
397  if (!skipUserDependent) {
398  importRealmAuthorizationSettings(rep, newRealm, session);
399  }
400 
401  if (rep.isInternationalizationEnabled() != null) {
402  newRealm.setInternationalizationEnabled(rep.isInternationalizationEnabled());
403  }
404  if (rep.getSupportedLocales() != null) {
405  newRealm.setSupportedLocales(new HashSet<String>(rep.getSupportedLocales()));
406  }
407  if (rep.getDefaultLocale() != null) {
408  newRealm.setDefaultLocale(rep.getDefaultLocale());
409  }
410 
411  // import attributes
412 
413  if (rep.getAttributes() != null) {
414  for (Map.Entry<String, String> attr : rep.getAttributes().entrySet()) {
415  newRealm.setAttribute(attr.getKey(), attr.getValue());
416  }
417  }
418 
419  if (newRealm.getComponents(newRealm.getId(), KeyProvider.class.getName()).isEmpty()) {
420  if (rep.getPrivateKey() != null) {
421  DefaultKeyProviders.createProviders(newRealm, rep.getPrivateKey(), rep.getCertificate());
422  } else {
423  DefaultKeyProviders.createProviders(newRealm);
424  }
425  }
426  }
static void convertDeprecatedClientTemplates(RealmRepresentation realm)
Definition: RepresentationToModel.java:798
static Map< String, ClientModel > createClients(KeycloakSession session, RealmRepresentation rep, RealmModel realm)
Definition: RepresentationToModel.java:1067
static UserModel createUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep)
Definition: RepresentationToModel.java:1498
static void importGroups(RealmModel realm, RealmRepresentation rep)
Definition: RepresentationToModel.java:533
static void importRealmAuthorizationSettings(RealmRepresentation rep, RealmModel newRealm, KeycloakSession session)
Definition: RepresentationToModel.java:1965
static void importUserFederationProvidersAndMappers(KeycloakSession session, RealmRepresentation rep, RealmModel newRealm)
Definition: RepresentationToModel.java:428
static Logger logger
Definition: RepresentationToModel.java:132
static Map< String, ClientScopeModel > createClientScopes(KeycloakSession session, List< ClientScopeRepresentation > clientScopes, RealmModel realm)
Definition: RepresentationToModel.java:1347
static void importRoles(RolesRepresentation realmRoles, RealmModel realm)
Definition: RepresentationToModel.java:491
static void importIdentityProviders(RealmRepresentation rep, RealmModel newRealm)
Definition: RepresentationToModel.java:1703
static void convertDeprecatedSocialProviders(RealmRepresentation rep)
Definition: RepresentationToModel.java:678
static void createClientScopeMappings(RealmModel realm, ClientModel clientModel, List< ScopeMappingRepresentation > mappings)
Definition: RepresentationToModel.java:1457
static void importComponents(RealmModel newRealm, MultivaluedHashMap< String, ComponentExportRepresentation > components, String parentId)
Definition: RepresentationToModel.java:471
static void importAuthenticationFlows(RealmModel newRealm, RealmRepresentation rep)
Definition: RepresentationToModel.java:585
static void convertDeprecatedApplications(KeycloakSession session, RealmRepresentation realm)
Definition: RepresentationToModel.java:729
static void importIdentityProviderMappers(RealmRepresentation rep, RealmModel newRealm)
Definition: RepresentationToModel.java:1711
static OTPPolicy toPolicy(RealmRepresentation rep)
Definition: RepresentationToModel.java:135
static void importFederatedUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep)
Definition: RepresentationToModel.java:2463
static ScopeContainerModel getScopeContainerHavingScope(RealmModel realm, ScopeMappingRepresentation scope)
Definition: RepresentationToModel.java:1471
static CredentialModel toModel(CredentialRepresentation cred)
Definition: RepresentationToModel.java:1639

◆ importRealmAuthorizationSettings()

static void org.keycloak.models.utils.RepresentationToModel.importRealmAuthorizationSettings ( RealmRepresentation  rep,
RealmModel  newRealm,
KeycloakSession  session 
)
inlinestatic
1965  {
1966  if (rep.getClients() != null) {
1967  rep.getClients().forEach(clientRepresentation -> {
1968  ClientModel client = newRealm.getClientByClientId(clientRepresentation.getClientId());
1969  importAuthorizationSettings(clientRepresentation, client, session);
1970  });
1971  }
1972  }
static void importAuthorizationSettings(ClientRepresentation clientRepresentation, ClientModel client, KeycloakSession session)
Definition: RepresentationToModel.java:1974

◆ importRoles()

static void org.keycloak.models.utils.RepresentationToModel.importRoles ( RolesRepresentation  realmRoles,
RealmModel  realm 
)
inlinestatic
491  {
492  if (realmRoles == null) return;
493 
494  if (realmRoles.getRealm() != null) { // realm roles
495  for (RoleRepresentation roleRep : realmRoles.getRealm()) {
496  createRole(realm, roleRep);
497  }
498  }
499  if (realmRoles.getClient() != null) {
500  for (Map.Entry<String, List<RoleRepresentation>> entry : realmRoles.getClient().entrySet()) {
501  ClientModel client = realm.getClientByClientId(entry.getKey());
502  if (client == null) {
503  throw new RuntimeException("App doesn't exist in role definitions: " + entry.getKey());
504  }
505  for (RoleRepresentation roleRep : entry.getValue()) {
506  // Application role may already exists (for example if it is defaultRole)
507  RoleModel role = roleRep.getId() != null ? client.addRole(roleRep.getId(), roleRep.getName()) : client.addRole(roleRep.getName());
508  role.setDescription(roleRep.getDescription());
509  }
510  }
511  }
512  // now that all roles are created, re-iterate and set up composites
513  if (realmRoles.getRealm() != null) { // realm roles
514  for (RoleRepresentation roleRep : realmRoles.getRealm()) {
515  RoleModel role = realm.getRole(roleRep.getName());
516  addComposites(role, roleRep, realm);
517  }
518  }
519  if (realmRoles.getClient() != null) {
520  for (Map.Entry<String, List<RoleRepresentation>> entry : realmRoles.getClient().entrySet()) {
521  ClientModel client = realm.getClientByClientId(entry.getKey());
522  if (client == null) {
523  throw new RuntimeException("App doesn't exist in role definitions: " + entry.getKey());
524  }
525  for (RoleRepresentation roleRep : entry.getValue()) {
526  RoleModel role = client.getRole(roleRep.getName());
527  addComposites(role, roleRep, realm);
528  }
529  }
530  }
531  }
static void createRole(RealmModel newRealm, RoleRepresentation roleRep)
Definition: RepresentationToModel.java:1033
static void addComposites(RoleModel role, RoleRepresentation roleRep, RealmModel realm)
Definition: RepresentationToModel.java:1038

◆ importUserFederationProvidersAndMappers()

static void org.keycloak.models.utils.RepresentationToModel.importUserFederationProvidersAndMappers ( KeycloakSession  session,
RealmRepresentation  rep,
RealmModel  newRealm 
)
inlinestatic
428  {
429  // providers to convert to component model
430  Set<String> convertSet = new HashSet<>();
431  convertSet.add(LDAPConstants.LDAP_PROVIDER);
432  convertSet.add("kerberos");
433  Map<String, String> mapperConvertSet = new HashMap<>();
434  mapperConvertSet.put(LDAPConstants.LDAP_PROVIDER, "org.keycloak.storage.ldap.mappers.LDAPStorageMapper");
435 
436 
437  Map<String, ComponentModel> userStorageModels = new HashMap<>();
438 
439  if (rep.getUserFederationProviders() != null) {
440  for (UserFederationProviderRepresentation fedRep : rep.getUserFederationProviders()) {
441  if (convertSet.contains(fedRep.getProviderName())) {
442  ComponentModel component = convertFedProviderToComponent(newRealm.getId(), fedRep);
443  userStorageModels.put(fedRep.getDisplayName(), newRealm.importComponentModel(component));
444  }
445  }
446  }
447 
448  // This is for case, when you have hand-written JSON file with LDAP userFederationProvider, but WITHOUT any userFederationMappers configured. Default LDAP mappers need to be created in that case.
449  Set<String> storageProvidersWhichShouldImportDefaultMappers = new HashSet<>(userStorageModels.keySet());
450 
451  if (rep.getUserFederationMappers() != null) {
452  for (UserFederationMapperRepresentation representation : rep.getUserFederationMappers()) {
453  if (userStorageModels.containsKey(representation.getFederationProviderDisplayName())) {
454  ComponentModel parent = userStorageModels.get(representation.getFederationProviderDisplayName());
455  String newMapperType = mapperConvertSet.get(parent.getProviderId());
456  ComponentModel mapper = convertFedMapperToComponent(newRealm, parent, representation, newMapperType);
457  newRealm.importComponentModel(mapper);
458 
459 
460  storageProvidersWhichShouldImportDefaultMappers.remove(representation.getFederationProviderDisplayName());
461 
462  }
463  }
464  }
465 
466  for (String providerDisplayName : storageProvidersWhichShouldImportDefaultMappers) {
467  ComponentUtil.notifyCreated(session, newRealm, userStorageModels.get(providerDisplayName));
468  }
469  }
static ComponentModel convertFedMapperToComponent(RealmModel realm, ComponentModel parent, UserFederationMapperRepresentation rep, String newMapperType)
Definition: RepresentationToModel.java:1015
void put(String key, String value)
Definition: ComponentModel.java:107
static ComponentModel convertFedProviderToComponent(String realmId, UserFederationProviderRepresentation fedModel)
Definition: RepresentationToModel.java:996

◆ removeEmptyString()

static Map<String, String> org.keycloak.models.utils.RepresentationToModel.removeEmptyString ( Map< String, String >  map)
inlinestaticprivate
2552  {
2553  if (map == null) {
2554  return null;
2555  }
2556 
2557  Map<String, String> m = new HashMap<>(map);
2558  for (Iterator<Map.Entry<String, String>> itr = m.entrySet().iterator(); itr.hasNext(); ) {
2559  Map.Entry<String, String> e = itr.next();
2560  if (e.getValue() == null || e.getValue().equals("")) {
2561  itr.remove();
2562  }
2563  }
2564  return m;
2565  }

◆ renameRealm()

static void org.keycloak.models.utils.RepresentationToModel.renameRealm ( RealmModel  realm,
String  name 
)
inlinestatic
820  {
821  if (name.equals(realm.getName())) return;
822 
823  String oldName = realm.getName();
824 
825  ClientModel masterApp = realm.getMasterAdminClient();
826  masterApp.setClientId(KeycloakModelUtils.getMasterRealmAdminApplicationClientId(name));
827  realm.setName(name);
828 
829  ClientModel adminClient = realm.getClientByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID);
830  if (adminClient != null) {
831  if (adminClient.getBaseUrl() != null) {
832  adminClient.setBaseUrl(adminClient.getBaseUrl().replace("/admin/" + oldName + "/", "/admin/" + name + "/"));
833  }
834  Set<String> adminRedirectUris = new HashSet<>();
835  for (String r : adminClient.getRedirectUris()) {
836  adminRedirectUris.add(replace(r, "/admin/" + oldName + "/", "/admin/" + name + "/"));
837  }
838  adminClient.setRedirectUris(adminRedirectUris);
839  }
840 
841  ClientModel accountClient = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
842  if (accountClient != null) {
843  if (accountClient.getBaseUrl() != null) {
844  accountClient.setBaseUrl(accountClient.getBaseUrl().replace("/realms/" + oldName + "/", "/realms/" + name + "/"));
845  }
846  Set<String> accountRedirectUris = new HashSet<>();
847  for (String r : accountClient.getRedirectUris()) {
848  accountRedirectUris.add(replace(r, "/realms/" + oldName + "/", "/realms/" + name + "/"));
849  }
850  accountClient.setRedirectUris(accountRedirectUris);
851  }
852  }
static String replace(String url, String target, String replacement)
Definition: RepresentationToModel.java:854

◆ replace()

static String org.keycloak.models.utils.RepresentationToModel.replace ( String  url,
String  target,
String  replacement 
)
inlinestaticprivate
854  {
855  return url != null ? url.replace(target, replacement) : null;
856  }

◆ toModel() [1/16]

static CredentialModel org.keycloak.models.utils.RepresentationToModel.toModel ( CredentialRepresentation  cred)
inlinestatic
1639  {
1640  CredentialModel model = new CredentialModel();
1641  model.setHashIterations(cred.getHashIterations());
1642  model.setCreatedDate(cred.getCreatedDate());
1643  model.setType(cred.getType());
1644  model.setDigits(cred.getDigits());
1645  model.setConfig(cred.getConfig());
1646  model.setDevice(cred.getDevice());
1647  model.setAlgorithm(cred.getAlgorithm());
1648  model.setCounter(cred.getCounter());
1649  model.setPeriod(cred.getPeriod());
1650  if (cred.getSalt() != null) {
1651  try {
1652  model.setSalt(Base64.decode(cred.getSalt()));
1653  } catch (IOException e) {
1654  throw new RuntimeException(e);
1655  }
1656  }
1657  model.setValue(cred.getValue());
1658  if (cred.getHashedSaltedValue() != null) {
1659  model.setValue(cred.getHashedSaltedValue());
1660  }
1661  return model;
1662 
1663  }

◆ toModel() [2/16]

static IdentityProviderModel org.keycloak.models.utils.RepresentationToModel.toModel ( RealmModel  realm,
IdentityProviderRepresentation  representation 
)
inlinestatic
1719  {
1720  IdentityProviderModel identityProviderModel = new IdentityProviderModel();
1721 
1722  identityProviderModel.setInternalId(representation.getInternalId());
1723  identityProviderModel.setAlias(representation.getAlias());
1724  identityProviderModel.setDisplayName(representation.getDisplayName());
1725  identityProviderModel.setProviderId(representation.getProviderId());
1726  identityProviderModel.setEnabled(representation.isEnabled());
1727  identityProviderModel.setLinkOnly(representation.isLinkOnly());
1728  identityProviderModel.setTrustEmail(representation.isTrustEmail());
1729  identityProviderModel.setAuthenticateByDefault(representation.isAuthenticateByDefault());
1730  identityProviderModel.setStoreToken(representation.isStoreToken());
1731  identityProviderModel.setAddReadTokenRoleOnCreate(representation.isAddReadTokenRoleOnCreate());
1732  identityProviderModel.setConfig(new HashMap<>(representation.getConfig()));
1733 
1734  String flowAlias = representation.getFirstBrokerLoginFlowAlias();
1735  if (flowAlias == null) {
1736  flowAlias = DefaultAuthenticationFlows.FIRST_BROKER_LOGIN_FLOW;
1737  }
1738 
1739  AuthenticationFlowModel flowModel = realm.getFlowByAlias(flowAlias);
1740  if (flowModel == null) {
1741  throw new ModelException("No available authentication flow with alias: " + flowAlias);
1742  }
1743  identityProviderModel.setFirstBrokerLoginFlowId(flowModel.getId());
1744 
1745  flowAlias = representation.getPostBrokerLoginFlowAlias();
1746  if (flowAlias == null || flowAlias.trim().length() == 0) {
1747  identityProviderModel.setPostBrokerLoginFlowId(null);
1748  } else {
1749  flowModel = realm.getFlowByAlias(flowAlias);
1750  if (flowModel == null) {
1751  throw new ModelException("No available authentication flow with alias: " + flowAlias);
1752  }
1753  identityProviderModel.setPostBrokerLoginFlowId(flowModel.getId());
1754  }
1755 
1756  return identityProviderModel;
1757  }

◆ toModel() [3/16]

static ProtocolMapperModel org.keycloak.models.utils.RepresentationToModel.toModel ( ProtocolMapperRepresentation  rep)
inlinestatic
1759  {
1760  ProtocolMapperModel model = new ProtocolMapperModel();
1761  model.setId(rep.getId());
1762  model.setName(rep.getName());
1763  model.setProtocol(rep.getProtocol());
1764  model.setProtocolMapper(rep.getProtocolMapper());
1765  model.setConfig(removeEmptyString(rep.getConfig()));
1766  return model;
1767  }
static Map< String, String > removeEmptyString(Map< String, String > map)
Definition: RepresentationToModel.java:2552

◆ toModel() [4/16]

static IdentityProviderMapperModel org.keycloak.models.utils.RepresentationToModel.toModel ( IdentityProviderMapperRepresentation  rep)
inlinestatic
1769  {
1770  IdentityProviderMapperModel model = new IdentityProviderMapperModel();
1771  model.setId(rep.getId());
1772  model.setName(rep.getName());
1773  model.setIdentityProviderAlias(rep.getIdentityProviderAlias());
1774  model.setIdentityProviderMapper(rep.getIdentityProviderMapper());
1775  model.setConfig(removeEmptyString(rep.getConfig()));
1776  return model;
1777  }
static Map< String, String > removeEmptyString(Map< String, String > map)
Definition: RepresentationToModel.java:2552

◆ toModel() [5/16]

static UserConsentModel org.keycloak.models.utils.RepresentationToModel.toModel ( RealmModel  newRealm,
UserConsentRepresentation  consentRep 
)
inlinestatic
1779  {
1780  ClientModel client = newRealm.getClientByClientId(consentRep.getClientId());
1781  if (client == null) {
1782  throw new RuntimeException("Unable to find client consent mappings for client: " + consentRep.getClientId());
1783  }
1784 
1785  UserConsentModel consentModel = new UserConsentModel(client);
1786  consentModel.setCreatedDate(consentRep.getCreatedDate());
1787  consentModel.setLastUpdatedDate(consentRep.getLastUpdatedDate());
1788 
1789  if (consentRep.getGrantedClientScopes() != null) {
1790  for (String scopeName : consentRep.getGrantedClientScopes()) {
1791  ClientScopeModel clientScope = KeycloakModelUtils.getClientScopeByName(newRealm, scopeName);
1792  if (clientScope == null) {
1793  throw new RuntimeException("Unable to find client scope referenced in consent mappings of user. Client scope name: " + scopeName);
1794  }
1795  consentModel.addGrantedClientScope(clientScope);
1796  }
1797  }
1798 
1799  // Backwards compatibility. If user had consent for "offline_access" role, we treat it as he has consent for "offline_access" client scope
1800  if (consentRep.getGrantedRealmRoles() != null) {
1801  if (consentRep.getGrantedRealmRoles().contains(OAuth2Constants.OFFLINE_ACCESS)) {
1802  ClientScopeModel offlineScope = client.getClientScopes(false, true).get(OAuth2Constants.OFFLINE_ACCESS);
1803  if (offlineScope == null) {
1804  logger.warn("Unable to find offline_access scope referenced in grantedRoles of user");
1805  }
1806  consentModel.addGrantedClientScope(offlineScope);
1807  }
1808  }
1809 
1810  return consentModel;
1811  }
static Logger logger
Definition: RepresentationToModel.java:132

◆ toModel() [6/16]

static AuthenticationFlowModel org.keycloak.models.utils.RepresentationToModel.toModel ( AuthenticationFlowRepresentation  rep)
inlinestatic
1813  {
1814  AuthenticationFlowModel model = new AuthenticationFlowModel();
1815  model.setId(rep.getId());
1816  model.setBuiltIn(rep.isBuiltIn());
1817  model.setTopLevel(rep.isTopLevel());
1818  model.setProviderId(rep.getProviderId());
1819  model.setAlias(rep.getAlias());
1820  model.setDescription(rep.getDescription());
1821  return model;
1822 
1823  }

◆ toModel() [7/16]

static AuthenticationExecutionModel org.keycloak.models.utils.RepresentationToModel.toModel ( RealmModel  realm,
AuthenticationExecutionExportRepresentation  rep 
)
inlinestatic
1825  {
1826  AuthenticationExecutionModel model = new AuthenticationExecutionModel();
1827  if (rep.getAuthenticatorConfig() != null) {
1828  AuthenticatorConfigModel config = realm.getAuthenticatorConfigByAlias(rep.getAuthenticatorConfig());
1829  model.setAuthenticatorConfig(config.getId());
1830  }
1831  model.setAuthenticator(rep.getAuthenticator());
1832  model.setAuthenticatorFlow(rep.isAutheticatorFlow());
1833  if (rep.getFlowAlias() != null) {
1834  AuthenticationFlowModel flow = realm.getFlowByAlias(rep.getFlowAlias());
1835  model.setFlowId(flow.getId());
1836  }
1837  model.setPriority(rep.getPriority());
1838  model.setRequirement(AuthenticationExecutionModel.Requirement.valueOf(rep.getRequirement()));
1839  return model;
1840  }

◆ toModel() [8/16]

static AuthenticationExecutionModel org.keycloak.models.utils.RepresentationToModel.toModel ( RealmModel  realm,
AuthenticationExecutionRepresentation  rep 
)
inlinestatic
1842  {
1843  AuthenticationExecutionModel model = new AuthenticationExecutionModel();
1844  model.setId(rep.getId());
1845  model.setFlowId(rep.getFlowId());
1846 
1847  model.setAuthenticator(rep.getAuthenticator());
1848  model.setPriority(rep.getPriority());
1849  model.setParentFlow(rep.getParentFlow());
1850  model.setAuthenticatorFlow(rep.isAutheticatorFlow());
1851  model.setRequirement(AuthenticationExecutionModel.Requirement.valueOf(rep.getRequirement()));
1852 
1853  if (rep.getAuthenticatorConfig() != null) {
1854  AuthenticatorConfigModel cfg = realm.getAuthenticatorConfigByAlias(rep.getAuthenticatorConfig());
1855  model.setAuthenticatorConfig(cfg.getId());
1856  }
1857  return model;
1858  }

◆ toModel() [9/16]

static AuthenticatorConfigModel org.keycloak.models.utils.RepresentationToModel.toModel ( AuthenticatorConfigRepresentation  rep)
inlinestatic
1860  {
1861  AuthenticatorConfigModel model = new AuthenticatorConfigModel();
1862  model.setAlias(rep.getAlias());
1863  model.setConfig(removeEmptyString(rep.getConfig()));
1864  return model;
1865  }
static Map< String, String > removeEmptyString(Map< String, String > map)
Definition: RepresentationToModel.java:2552

◆ toModel() [10/16]

static RequiredActionProviderModel org.keycloak.models.utils.RepresentationToModel.toModel ( RequiredActionProviderRepresentation  rep)
inlinestatic
1867  {
1868  RequiredActionProviderModel model = new RequiredActionProviderModel();
1869  model.setConfig(rep.getConfig());
1870  model.setPriority(rep.getPriority());
1871  model.setDefaultAction(rep.isDefaultAction());
1872  model.setEnabled(rep.isEnabled());
1873  model.setProviderId(rep.getProviderId());
1874  model.setName(rep.getName());
1875  model.setAlias(rep.getAlias());
1876  return model;
1877  }

◆ toModel() [11/16]

static ComponentModel org.keycloak.models.utils.RepresentationToModel.toModel ( KeycloakSession  session,
ComponentRepresentation  rep 
)
inlinestatic
1879  {
1880  ComponentModel model = new ComponentModel();
1881  model.setId(rep.getId());
1882  model.setParentId(rep.getParentId());
1883  model.setProviderType(rep.getProviderType());
1884  model.setProviderId(rep.getProviderId());
1885  model.setConfig(new MultivaluedHashMap<>());
1886  model.setName(rep.getName());
1887  model.setSubType(rep.getSubType());
1888 
1889  if (rep.getConfig() != null) {
1890  Set<String> keys = new HashSet<>(rep.getConfig().keySet());
1891  for (String k : keys) {
1892  List<String> values = rep.getConfig().get(k);
1893  if (values != null) {
1894  ListIterator<String> itr = values.listIterator();
1895  while (itr.hasNext()) {
1896  String v = itr.next();
1897  if (v == null || v.trim().isEmpty()) {
1898  itr.remove();
1899  }
1900  }
1901 
1902  if (!values.isEmpty()) {
1903  model.getConfig().put(k, values);
1904  }
1905  }
1906  }
1907  }
1908 
1909  return model;
1910  }

◆ toModel() [12/16]

static ResourceServer org.keycloak.models.utils.RepresentationToModel.toModel ( ResourceServerRepresentation  rep,
AuthorizationProvider  authorization 
)
inlinestatic
1995  {
1996  ResourceServerStore resourceServerStore = authorization.getStoreFactory().getResourceServerStore();
1997  ResourceServer resourceServer;
1998  ResourceServer existing = resourceServerStore.findById(rep.getClientId());
1999 
2000  if (existing == null) {
2001  resourceServer = resourceServerStore.create(rep.getClientId());
2002  resourceServer.setAllowRemoteResourceManagement(true);
2003  resourceServer.setPolicyEnforcementMode(PolicyEnforcementMode.ENFORCING);
2004  } else {
2005  resourceServer = existing;
2006  }
2007 
2008  resourceServer.setPolicyEnforcementMode(rep.getPolicyEnforcementMode());
2009  resourceServer.setAllowRemoteResourceManagement(rep.isAllowRemoteResourceManagement());
2010 
2011  for (ScopeRepresentation scope : rep.getScopes()) {
2012  toModel(scope, resourceServer, authorization);
2013  }
2014 
2015  KeycloakSession session = authorization.getKeycloakSession();
2016  RealmModel realm = authorization.getRealm();
2017 
2018  for (ResourceRepresentation resource : rep.getResources()) {
2019  ResourceOwnerRepresentation owner = resource.getOwner();
2020 
2021  if (owner == null) {
2022  owner = new ResourceOwnerRepresentation();
2023  owner.setId(resourceServer.getId());
2024  resource.setOwner(owner);
2025  } else if (owner.getName() != null) {
2026  UserModel user = session.users().getUserByUsername(owner.getName(), realm);
2027 
2028  if (user != null) {
2029  owner.setId(user.getId());
2030  }
2031  }
2032 
2033  toModel(resource, resourceServer, authorization);
2034  }
2035 
2036  importPolicies(authorization, resourceServer, rep.getPolicies(), null);
2037 
2038  return resourceServer;
2039  }
static Policy importPolicies(AuthorizationProvider authorization, ResourceServer resourceServer, List< PolicyRepresentation > policiesToImport, String parentPolicyName)
Definition: RepresentationToModel.java:2041
static CredentialModel toModel(CredentialRepresentation cred)
Definition: RepresentationToModel.java:1639

◆ toModel() [13/16]

static Policy org.keycloak.models.utils.RepresentationToModel.toModel ( AbstractPolicyRepresentation  representation,
AuthorizationProvider  authorization,
Policy  model 
)
inlinestatic
2101  {
2102  model.setName(representation.getName());
2103  model.setDescription(representation.getDescription());
2104  model.setDecisionStrategy(representation.getDecisionStrategy());
2105  model.setLogic(representation.getLogic());
2106 
2107  Set resources = representation.getResources();
2108  Set scopes = representation.getScopes();
2109  Set policies = representation.getPolicies();
2110 
2111  if (representation instanceof PolicyRepresentation) {
2112  PolicyRepresentation policy = PolicyRepresentation.class.cast(representation);
2113 
2114  if (resources == null) {
2115  String resourcesConfig = policy.getConfig().get("resources");
2116 
2117  if (resourcesConfig != null) {
2118  try {
2119  resources = JsonSerialization.readValue(resourcesConfig, Set.class);
2120  } catch (IOException e) {
2121  throw new RuntimeException(e);
2122  }
2123  }
2124  }
2125 
2126  if (scopes == null) {
2127  String scopesConfig = policy.getConfig().get("scopes");
2128 
2129  if (scopesConfig != null) {
2130  try {
2131  scopes = JsonSerialization.readValue(scopesConfig, Set.class);
2132  } catch (IOException e) {
2133  throw new RuntimeException(e);
2134  }
2135  }
2136  }
2137 
2138  if (policies == null) {
2139  String policiesConfig = policy.getConfig().get("applyPolicies");
2140 
2141  if (policiesConfig != null) {
2142  try {
2143  policies = JsonSerialization.readValue(policiesConfig, Set.class);
2144  } catch (IOException e) {
2145  throw new RuntimeException(e);
2146  }
2147  }
2148  }
2149 
2150  model.setConfig(policy.getConfig());
2151  }
2152 
2153  StoreFactory storeFactory = authorization.getStoreFactory();
2154 
2155  updateResources(resources, model, storeFactory);
2156  updateScopes(scopes, model, storeFactory);
2157  updateAssociatedPolicies(policies, model, storeFactory);
2158 
2159  PolicyProviderFactory provider = authorization.getProviderFactory(model.getType());
2160 
2161  if (representation instanceof PolicyRepresentation) {
2162  provider.onImport(model, PolicyRepresentation.class.cast(representation), authorization);
2163  } else if (representation.getId() == null) {
2164  provider.onCreate(model, representation, authorization);
2165  } else {
2166  provider.onUpdate(model, representation, authorization);
2167  }
2168 
2169 
2170  representation.setId(model.getId());
2171 
2172  return model;
2173  }
static void updateAssociatedPolicies(Set< String > policyIds, Policy policy, StoreFactory storeFactory)
Definition: RepresentationToModel.java:2223
static void updateScopes(Set< String > scopeIds, Policy policy, StoreFactory storeFactory)
Definition: RepresentationToModel.java:2175
static void updateResources(Set< String > resourceIds, Policy policy, StoreFactory storeFactory)
Definition: RepresentationToModel.java:2276

◆ toModel() [14/16]

static Resource org.keycloak.models.utils.RepresentationToModel.toModel ( ResourceRepresentation  resource,
ResourceServer  resourceServer,
AuthorizationProvider  authorization 
)
inlinestatic
2322  {
2323  ResourceStore resourceStore = authorization.getStoreFactory().getResourceStore();
2324  ResourceOwnerRepresentation owner = resource.getOwner();
2325 
2326  if (owner == null) {
2327  owner = new ResourceOwnerRepresentation();
2328  owner.setId(resourceServer.getId());
2329  }
2330 
2331  String ownerId = owner.getId();
2332 
2333  if (ownerId == null) {
2334  ownerId = resourceServer.getId();
2335  }
2336 
2337  if (!resourceServer.getId().equals(ownerId)) {
2338  RealmModel realm = authorization.getRealm();
2339  KeycloakSession keycloakSession = authorization.getKeycloakSession();
2340  UserProvider users = keycloakSession.users();
2341  UserModel ownerModel = users.getUserById(ownerId, realm);
2342 
2343  if (ownerModel == null) {
2344  ownerModel = users.getUserByUsername(ownerId, realm);
2345  }
2346 
2347  if (ownerModel == null) {
2348  throw new RuntimeException("Owner must be a valid username or user identifier. If the resource server, the client id or null.");
2349  }
2350 
2351  ownerId = ownerModel.getId();
2352  }
2353 
2354  Resource existing;
2355 
2356  if (resource.getId() != null) {
2357  existing = resourceStore.findById(resource.getId(), resourceServer.getId());
2358  } else {
2359  existing = resourceStore.findByName(resource.getName(), ownerId, resourceServer.getId());
2360  }
2361 
2362  if (existing != null) {
2363  existing.setName(resource.getName());
2364  existing.setDisplayName(resource.getDisplayName());
2365  existing.setType(resource.getType());
2366  existing.updateUris(resource.getUris());
2367  existing.setIconUri(resource.getIconUri());
2368  existing.setOwnerManagedAccess(Boolean.TRUE.equals(resource.getOwnerManagedAccess()));
2369  existing.updateScopes(resource.getScopes().stream()
2370  .map((ScopeRepresentation scope) -> toModel(scope, resourceServer, authorization))
2371  .collect(Collectors.toSet()));
2372  Map<String, List<String>> attributes = resource.getAttributes();
2373 
2374  if (attributes != null) {
2375  Set<String> existingAttrNames = existing.getAttributes().keySet();
2376 
2377  for (String name : existingAttrNames) {
2378  if (attributes.containsKey(name)) {
2379  existing.setAttribute(name, attributes.get(name));
2380  attributes.remove(name);
2381  } else {
2382  existing.removeAttribute(name);
2383  }
2384  }
2385 
2386  for (String name : attributes.keySet()) {
2387  existing.setAttribute(name, attributes.get(name));
2388  }
2389  }
2390 
2391  return existing;
2392  }
2393 
2394  Resource model = resourceStore.create(resource.getId(), resource.getName(), resourceServer, ownerId);
2395 
2396  model.setDisplayName(resource.getDisplayName());
2397  model.setType(resource.getType());
2398  model.updateUris(resource.getUris());
2399  model.setIconUri(resource.getIconUri());
2400  model.setOwnerManagedAccess(Boolean.TRUE.equals(resource.getOwnerManagedAccess()));
2401 
2402  Set<ScopeRepresentation> scopes = resource.getScopes();
2403 
2404  if (scopes != null) {
2405  model.updateScopes(scopes.stream().map((Function<ScopeRepresentation, Scope>) scope -> toModel(scope, resourceServer, authorization)).collect(Collectors.toSet()));
2406  }
2407 
2408  Map<String, List<String>> attributes = resource.getAttributes();
2409 
2410  if (attributes != null) {
2411  for (Entry<String, List<String>> entry : attributes.entrySet()) {
2412  model.setAttribute(entry.getKey(), entry.getValue());
2413  }
2414  }
2415 
2416  resource.setId(model.getId());
2417 
2418  return model;
2419  }
static CredentialModel toModel(CredentialRepresentation cred)
Definition: RepresentationToModel.java:1639

◆ toModel() [15/16]

static Scope org.keycloak.models.utils.RepresentationToModel.toModel ( ScopeRepresentation  scope,
ResourceServer  resourceServer,
AuthorizationProvider  authorization 
)
inlinestatic
2421  {
2422  StoreFactory storeFactory = authorization.getStoreFactory();
2423  ScopeStore scopeStore = storeFactory.getScopeStore();
2424  Scope existing;
2425 
2426  if (scope.getId() != null) {
2427  existing = scopeStore.findById(scope.getId(), resourceServer.getId());
2428  } else {
2429  existing = scopeStore.findByName(scope.getName(), resourceServer.getId());
2430  }
2431 
2432  if (existing != null) {
2433  existing.setName(scope.getName());
2434  existing.setDisplayName(scope.getDisplayName());
2435  existing.setIconUri(scope.getIconUri());
2436  return existing;
2437  }
2438 
2439  Scope model = scopeStore.create(scope.getId(), scope.getName(), resourceServer);
2440 
2441  model.setDisplayName(scope.getDisplayName());
2442  model.setIconUri(scope.getIconUri());
2443 
2444  scope.setId(model.getId());
2445 
2446  return model;
2447  }

◆ toModel() [16/16]

static PermissionTicket org.keycloak.models.utils.RepresentationToModel.toModel ( PermissionTicketRepresentation  representation,
String  resourceServerId,
AuthorizationProvider  authorization 
)
inlinestatic
2449  {
2450  PermissionTicketStore ticketStore = authorization.getStoreFactory().getPermissionTicketStore();
2451  PermissionTicket ticket = ticketStore.findById(representation.getId(), resourceServerId);
2452  boolean granted = representation.isGranted();
2453 
2454  if (granted && !ticket.isGranted()) {
2455  ticket.setGrantedTimestamp(System.currentTimeMillis());
2456  } else if (!granted) {
2457  ticketStore.delete(ticket.getId());
2458  }
2459 
2460  return ticket;
2461  }

◆ toPolicy()

static OTPPolicy org.keycloak.models.utils.RepresentationToModel.toPolicy ( RealmRepresentation  rep)
inlinestatic
135  {
136  OTPPolicy policy = new OTPPolicy();
137  if (rep.getOtpPolicyType() != null) policy.setType(rep.getOtpPolicyType());
138  if (rep.getOtpPolicyLookAheadWindow() != null) policy.setLookAheadWindow(rep.getOtpPolicyLookAheadWindow());
139  if (rep.getOtpPolicyInitialCounter() != null) policy.setInitialCounter(rep.getOtpPolicyInitialCounter());
140  if (rep.getOtpPolicyAlgorithm() != null) policy.setAlgorithm(rep.getOtpPolicyAlgorithm());
141  if (rep.getOtpPolicyDigits() != null) policy.setDigits(rep.getOtpPolicyDigits());
142  if (rep.getOtpPolicyPeriod() != null) policy.setPeriod(rep.getOtpPolicyPeriod());
143  return policy;
144 
145  }

◆ updateAssociatedPolicies()

static void org.keycloak.models.utils.RepresentationToModel.updateAssociatedPolicies ( Set< String >  policyIds,
Policy  policy,
StoreFactory  storeFactory 
)
inlinestaticprivate
2223  {
2224  ResourceServer resourceServer = policy.getResourceServer();
2225 
2226  if (policyIds != null) {
2227  if (policyIds.isEmpty()) {
2228  for (Policy associated: new HashSet<Policy>(policy.getAssociatedPolicies())) {
2229  policy.removeAssociatedPolicy(associated);
2230  }
2231  return;
2232  }
2233 
2234  PolicyStore policyStore = storeFactory.getPolicyStore();
2235 
2236  for (String policyId : policyIds) {
2237  boolean hasPolicy = false;
2238 
2239  for (Policy policyModel : new HashSet<Policy>(policy.getAssociatedPolicies())) {
2240  if (policyModel.getId().equals(policyId) || policyModel.getName().equals(policyId)) {
2241  hasPolicy = true;
2242  }
2243  }
2244 
2245  if (!hasPolicy) {
2246  Policy associatedPolicy = policyStore.findById(policyId, resourceServer.getId());
2247 
2248  if (associatedPolicy == null) {
2249  associatedPolicy = policyStore.findByName(policyId, resourceServer.getId());
2250  if (associatedPolicy == null) {
2251  throw new RuntimeException("Policy with id or name [" + policyId + "] does not exist");
2252  }
2253  }
2254 
2255  policy.addAssociatedPolicy(associatedPolicy);
2256  }
2257  }
2258 
2259  for (Policy policyModel : new HashSet<Policy>(policy.getAssociatedPolicies())) {
2260  boolean hasPolicy = false;
2261 
2262  for (String policyId : policyIds) {
2263  if (policyModel.getId().equals(policyId) || policyModel.getName().equals(policyId)) {
2264  hasPolicy = true;
2265  }
2266  }
2267  if (!hasPolicy) {
2268  policy.removeAssociatedPolicy(policyModel);
2269  }
2270  }
2271  }
2272 
2273  policy.removeConfig("applyPolicies");
2274  }

◆ updateClient()

static void org.keycloak.models.utils.RepresentationToModel.updateClient ( ClientRepresentation  rep,
ClientModel  resource 
)
inlinestatic
1266  {
1267  if (rep.getClientId() != null) resource.setClientId(rep.getClientId());
1268  if (rep.getName() != null) resource.setName(rep.getName());
1269  if (rep.getDescription() != null) resource.setDescription(rep.getDescription());
1270  if (rep.isEnabled() != null) resource.setEnabled(rep.isEnabled());
1271  if (rep.isBearerOnly() != null) resource.setBearerOnly(rep.isBearerOnly());
1272  if (rep.isConsentRequired() != null) resource.setConsentRequired(rep.isConsentRequired());
1273  if (rep.isStandardFlowEnabled() != null) resource.setStandardFlowEnabled(rep.isStandardFlowEnabled());
1274  if (rep.isImplicitFlowEnabled() != null) resource.setImplicitFlowEnabled(rep.isImplicitFlowEnabled());
1275  if (rep.isDirectAccessGrantsEnabled() != null)
1276  resource.setDirectAccessGrantsEnabled(rep.isDirectAccessGrantsEnabled());
1277  if (rep.isServiceAccountsEnabled() != null) resource.setServiceAccountsEnabled(rep.isServiceAccountsEnabled());
1278  if (rep.isPublicClient() != null) resource.setPublicClient(rep.isPublicClient());
1279  if (rep.isFullScopeAllowed() != null) resource.setFullScopeAllowed(rep.isFullScopeAllowed());
1280  if (rep.isFrontchannelLogout() != null) resource.setFrontchannelLogout(rep.isFrontchannelLogout());
1281  if (rep.getRootUrl() != null) resource.setRootUrl(rep.getRootUrl());
1282  if (rep.getAdminUrl() != null) resource.setManagementUrl(rep.getAdminUrl());
1283  if (rep.getBaseUrl() != null) resource.setBaseUrl(rep.getBaseUrl());
1284  if (rep.isSurrogateAuthRequired() != null) resource.setSurrogateAuthRequired(rep.isSurrogateAuthRequired());
1285  if (rep.getNodeReRegistrationTimeout() != null)
1286  resource.setNodeReRegistrationTimeout(rep.getNodeReRegistrationTimeout());
1287  if (rep.getClientAuthenticatorType() != null)
1288  resource.setClientAuthenticatorType(rep.getClientAuthenticatorType());
1289 
1290  if (rep.getProtocol() != null) resource.setProtocol(rep.getProtocol());
1291  if (rep.getAttributes() != null) {
1292  for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) {
1293  resource.setAttribute(entry.getKey(), entry.getValue());
1294  }
1295  }
1296  if (rep.getAttributes() != null) {
1297  for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) {
1298  resource.setAttribute(entry.getKey(), entry.getValue());
1299  }
1300  }
1301 
1302  if (rep.getAuthenticationFlowBindingOverrides() != null) {
1303  for (Map.Entry<String, String> entry : rep.getAuthenticationFlowBindingOverrides().entrySet()) {
1304  if (entry.getValue() == null || entry.getValue().trim().equals("")) {
1305  resource.removeAuthenticationFlowBindingOverride(entry.getKey());
1306  } else {
1307  String flowId = entry.getValue();
1308  if (resource.getRealm().getAuthenticationFlowById(flowId) == null) {
1309  throw new RuntimeException("Unable to resolve auth flow binding override for: " + entry.getKey());
1310  }
1311  resource.setAuthenticationFlowBindingOverride(entry.getKey(), entry.getValue());
1312  }
1313  }
1314  }
1315 
1316 
1317  if (rep.getNotBefore() != null) {
1318  resource.setNotBefore(rep.getNotBefore());
1319  }
1320  if (rep.getDefaultRoles() != null) {
1321  resource.updateDefaultRoles(rep.getDefaultRoles());
1322  }
1323 
1324  List<String> redirectUris = rep.getRedirectUris();
1325  if (redirectUris != null) {
1326  resource.setRedirectUris(new HashSet<String>(redirectUris));
1327  }
1328 
1329  List<String> webOrigins = rep.getWebOrigins();
1330  if (webOrigins != null) {
1331  resource.setWebOrigins(new HashSet<String>(webOrigins));
1332  }
1333 
1334  if (rep.getRegisteredNodes() != null) {
1335  for (Map.Entry<String, Integer> entry : rep.getRegisteredNodes().entrySet()) {
1336  resource.registerNode(entry.getKey(), entry.getValue());
1337  }
1338  }
1339 
1340  if (rep.getSecret() != null) resource.setSecret(rep.getSecret());
1341 
1342  resource.updateClient();
1343  }

◆ updateClientScope()

static void org.keycloak.models.utils.RepresentationToModel.updateClientScope ( ClientScopeRepresentation  rep,
ClientScopeModel  resource 
)
inlinestatic
1384  {
1385  if (rep.getName() != null) resource.setName(rep.getName());
1386  if (rep.getDescription() != null) resource.setDescription(rep.getDescription());
1387 
1388 
1389  if (rep.getProtocol() != null) resource.setProtocol(rep.getProtocol());
1390 
1391  if (rep.getAttributes() != null) {
1392  for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) {
1393  resource.setAttribute(entry.getKey(), entry.getValue());
1394  }
1395  }
1396 
1397  }

◆ updateComponent()

static void org.keycloak.models.utils.RepresentationToModel.updateComponent ( KeycloakSession  session,
ComponentRepresentation  rep,
ComponentModel  component,
boolean  internal 
)
inlinestatic
1912  {
1913  if (rep.getName() != null) {
1914  component.setName(rep.getName());
1915  }
1916 
1917  if (rep.getParentId() != null) {
1918  component.setParentId(rep.getParentId());
1919  }
1920 
1921  if (rep.getProviderType() != null) {
1922  component.setProviderType(rep.getProviderType());
1923  }
1924 
1925  if (rep.getProviderId() != null) {
1926  component.setProviderId(rep.getProviderId());
1927  }
1928 
1929  if (rep.getSubType() != null) {
1930  component.setSubType(rep.getSubType());
1931  }
1932 
1933  Map<String, ProviderConfigProperty> providerConfiguration = null;
1934  if (!internal) {
1935  providerConfiguration = ComponentUtil.getComponentConfigProperties(session, component);
1936  }
1937 
1938  if (rep.getConfig() != null) {
1939  Set<String> keys = new HashSet<>(rep.getConfig().keySet());
1940  for (String k : keys) {
1941  if (!internal && !providerConfiguration.containsKey(k)) {
1942  break;
1943  }
1944 
1945  List<String> values = rep.getConfig().get(k);
1946  if (values == null || values.isEmpty() || values.get(0) == null || values.get(0).trim().isEmpty()) {
1947  component.getConfig().remove(k);
1948  } else {
1949  ListIterator<String> itr = values.listIterator();
1950  while (itr.hasNext()) {
1951  String v = itr.next();
1952  if (v == null || v.trim().isEmpty() || v.equals(ComponentRepresentation.SECRET_VALUE)) {
1953  itr.remove();
1954  }
1955  }
1956 
1957  if (!values.isEmpty()) {
1958  component.getConfig().put(k, values);
1959  }
1960  }
1961  }
1962  }
1963  }

◆ updateCredential()

static void org.keycloak.models.utils.RepresentationToModel.updateCredential ( KeycloakSession  session,
RealmModel  realm,
UserModel  user,
CredentialRepresentation  cred,
boolean  adminRequest 
)
inlinestaticprivate
1573  {
1574  if (cred.getValue() != null) {
1575  PasswordUserCredentialModel plainTextCred = convertCredential(cred);
1576  plainTextCred.setAdminRequest(adminRequest);
1577 
1578  //if called from import we need to change realm in context to load password policies from the newly created realm
1579  RealmModel origRealm = session.getContext().getRealm();
1580  try {
1581  session.getContext().setRealm(realm);
1582  session.userCredentialManager().updateCredential(realm, user, plainTextCred);
1583  } catch (ModelException ex) {
1584  throw new PasswordPolicyNotMetException(ex.getMessage(), user.getUsername(), ex);
1585  } finally {
1586  session.getContext().setRealm(origRealm);
1587  }
1588  } else {
1589  CredentialModel hashedCred = new CredentialModel();
1590  hashedCred.setType(cred.getType());
1591  hashedCred.setDevice(cred.getDevice());
1592  if (cred.getHashIterations() != null) hashedCred.setHashIterations(cred.getHashIterations());
1593  try {
1594  if (cred.getSalt() != null) hashedCred.setSalt(Base64.decode(cred.getSalt()));
1595  } catch (IOException ioe) {
1596  throw new RuntimeException(ioe);
1597  }
1598  hashedCred.setValue(cred.getHashedSaltedValue());
1599  if (cred.getCounter() != null) hashedCred.setCounter(cred.getCounter());
1600  if (cred.getDigits() != null) hashedCred.setDigits(cred.getDigits());
1601 
1602  if (cred.getAlgorithm() != null) {
1603 
1604  // Could happen when migrating from some early version
1605  if ((UserCredentialModel.PASSWORD.equals(cred.getType()) || UserCredentialModel.PASSWORD_HISTORY.equals(cred.getType())) &&
1606  (cred.getAlgorithm().equals(HmacOTP.HMAC_SHA1))) {
1607  hashedCred.setAlgorithm("pbkdf2");
1608  } else {
1609  hashedCred.setAlgorithm(cred.getAlgorithm());
1610  }
1611 
1612  } else {
1613  if (UserCredentialModel.PASSWORD.equals(cred.getType()) || UserCredentialModel.PASSWORD_HISTORY.equals(cred.getType())) {
1614  hashedCred.setAlgorithm("pbkdf2");
1615  } else if (UserCredentialModel.isOtp(cred.getType())) {
1616  hashedCred.setAlgorithm(HmacOTP.HMAC_SHA1);
1617  }
1618  }
1619 
1620  if (cred.getPeriod() != null) hashedCred.setPeriod(cred.getPeriod());
1621  if (cred.getDigits() == null && UserCredentialModel.isOtp(cred.getType())) {
1622  hashedCred.setDigits(6);
1623  }
1624  if (cred.getPeriod() == null && UserCredentialModel.TOTP.equals(cred.getType())) {
1625  hashedCred.setPeriod(30);
1626  }
1627  hashedCred.setCreatedDate(cred.getCreatedDate());
1628  session.userCredentialManager().createCredential(realm, user, hashedCred);
1629  }
1630  }
static PasswordUserCredentialModel convertCredential(CredentialRepresentation cred)
Definition: RepresentationToModel.java:1632

◆ updateRealm()

static void org.keycloak.models.utils.RepresentationToModel.updateRealm ( RealmRepresentation  rep,
RealmModel  realm,
KeycloakSession  session 
)
inlinestatic
858  {
859  if (rep.getRealm() != null) {
860  renameRealm(realm, rep.getRealm());
861  }
862 
863  // Import attributes first, so the stuff saved directly on representation (displayName, bruteForce etc) has bigger priority
864  if (rep.getAttributes() != null) {
865  Set<String> attrsToRemove = new HashSet<>(realm.getAttributes().keySet());
866  attrsToRemove.removeAll(rep.getAttributes().keySet());
867 
868  for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) {
869  realm.setAttribute(entry.getKey(), entry.getValue());
870  }
871 
872  for (String attr : attrsToRemove) {
873  realm.removeAttribute(attr);
874  }
875  }
876 
877  if (rep.getDisplayName() != null) realm.setDisplayName(rep.getDisplayName());
878  if (rep.getDisplayNameHtml() != null) realm.setDisplayNameHtml(rep.getDisplayNameHtml());
879  if (rep.isEnabled() != null) realm.setEnabled(rep.isEnabled());
880  if (rep.isUserManagedAccessAllowed() != null) realm.setUserManagedAccessAllowed(rep.isUserManagedAccessAllowed());
881  if (rep.isBruteForceProtected() != null) realm.setBruteForceProtected(rep.isBruteForceProtected());
882  if (rep.isPermanentLockout() != null) realm.setPermanentLockout(rep.isPermanentLockout());
883  if (rep.getMaxFailureWaitSeconds() != null) realm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds());
884  if (rep.getMinimumQuickLoginWaitSeconds() != null)
885  realm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds());
886  if (rep.getWaitIncrementSeconds() != null) realm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds());
887  if (rep.getQuickLoginCheckMilliSeconds() != null)
888  realm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds());
889  if (rep.getMaxDeltaTimeSeconds() != null) realm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds());
890  if (rep.getFailureFactor() != null) realm.setFailureFactor(rep.getFailureFactor());
891  if (rep.isRegistrationAllowed() != null) realm.setRegistrationAllowed(rep.isRegistrationAllowed());
892  if (rep.isRegistrationEmailAsUsername() != null)
893  realm.setRegistrationEmailAsUsername(rep.isRegistrationEmailAsUsername());
894  if (rep.isRememberMe() != null) realm.setRememberMe(rep.isRememberMe());
895  if (rep.isVerifyEmail() != null) realm.setVerifyEmail(rep.isVerifyEmail());
896  if (rep.isLoginWithEmailAllowed() != null) realm.setLoginWithEmailAllowed(rep.isLoginWithEmailAllowed());
897  if (rep.isDuplicateEmailsAllowed() != null) realm.setDuplicateEmailsAllowed(rep.isDuplicateEmailsAllowed());
898  if (rep.isResetPasswordAllowed() != null) realm.setResetPasswordAllowed(rep.isResetPasswordAllowed());
899  if (rep.isEditUsernameAllowed() != null) realm.setEditUsernameAllowed(rep.isEditUsernameAllowed());
900  if (rep.getSslRequired() != null) realm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase()));
901  if (rep.getAccessCodeLifespan() != null) realm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
902  if (rep.getAccessCodeLifespanUserAction() != null)
903  realm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction());
904  if (rep.getAccessCodeLifespanLogin() != null)
905  realm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin());
906  if (rep.getActionTokenGeneratedByAdminLifespan() != null)
907  realm.setActionTokenGeneratedByAdminLifespan(rep.getActionTokenGeneratedByAdminLifespan());
908  if (rep.getActionTokenGeneratedByUserLifespan() != null)
909  realm.setActionTokenGeneratedByUserLifespan(rep.getActionTokenGeneratedByUserLifespan());
910  if (rep.getNotBefore() != null) realm.setNotBefore(rep.getNotBefore());
911  if (rep.getDefaultSignatureAlgorithm() != null) realm.setDefaultSignatureAlgorithm(rep.getDefaultSignatureAlgorithm());
912  if (rep.getRevokeRefreshToken() != null) realm.setRevokeRefreshToken(rep.getRevokeRefreshToken());
913  if (rep.getRefreshTokenMaxReuse() != null) realm.setRefreshTokenMaxReuse(rep.getRefreshTokenMaxReuse());
914  if (rep.getAccessTokenLifespan() != null) realm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
915  if (rep.getAccessTokenLifespanForImplicitFlow() != null)
916  realm.setAccessTokenLifespanForImplicitFlow(rep.getAccessTokenLifespanForImplicitFlow());
917  if (rep.getSsoSessionIdleTimeout() != null) realm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout());
918  if (rep.getSsoSessionMaxLifespan() != null) realm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan());
919  if (rep.getOfflineSessionIdleTimeout() != null)
920  realm.setOfflineSessionIdleTimeout(rep.getOfflineSessionIdleTimeout());
921  // KEYCLOAK-7688 Offline Session Max for Offline Token
922  if (rep.getOfflineSessionMaxLifespanEnabled() != null) realm.setOfflineSessionMaxLifespanEnabled(rep.getOfflineSessionMaxLifespanEnabled());
923  if (rep.getOfflineSessionMaxLifespan() != null)
924  realm.setOfflineSessionMaxLifespan(rep.getOfflineSessionMaxLifespan());
925  if (rep.getRequiredCredentials() != null) {
926  realm.updateRequiredCredentials(rep.getRequiredCredentials());
927  }
928  if (rep.getLoginTheme() != null) realm.setLoginTheme(rep.getLoginTheme());
929  if (rep.getAccountTheme() != null) realm.setAccountTheme(rep.getAccountTheme());
930  if (rep.getAdminTheme() != null) realm.setAdminTheme(rep.getAdminTheme());
931  if (rep.getEmailTheme() != null) realm.setEmailTheme(rep.getEmailTheme());
932 
933  if (rep.isEventsEnabled() != null) realm.setEventsEnabled(rep.isEventsEnabled());
934  if (rep.getEventsExpiration() != null) realm.setEventsExpiration(rep.getEventsExpiration());
935  if (rep.getEventsListeners() != null) realm.setEventsListeners(new HashSet<>(rep.getEventsListeners()));
936  if (rep.getEnabledEventTypes() != null) realm.setEnabledEventTypes(new HashSet<>(rep.getEnabledEventTypes()));
937 
938  if (rep.isAdminEventsEnabled() != null) realm.setAdminEventsEnabled(rep.isAdminEventsEnabled());
939  if (rep.isAdminEventsDetailsEnabled() != null)
940  realm.setAdminEventsDetailsEnabled(rep.isAdminEventsDetailsEnabled());
941 
942 
943  if (rep.getPasswordPolicy() != null)
944  realm.setPasswordPolicy(PasswordPolicy.parse(session, rep.getPasswordPolicy()));
945  if (rep.getOtpPolicyType() != null) realm.setOTPPolicy(toPolicy(rep));
946 
947  if (rep.getDefaultRoles() != null) {
948  realm.updateDefaultRoles(rep.getDefaultRoles().toArray(new String[rep.getDefaultRoles().size()]));
949  }
950 
951  if (rep.getSmtpServer() != null) {
952  Map<String, String> config = new HashMap(rep.getSmtpServer());
953  if (rep.getSmtpServer().containsKey("password") && ComponentRepresentation.SECRET_VALUE.equals(rep.getSmtpServer().get("password"))) {
954  String passwordValue = realm.getSmtpConfig() != null ? realm.getSmtpConfig().get("password") : null;
955  config.put("password", passwordValue);
956  }
957  realm.setSmtpConfig(config);
958  }
959 
960  if (rep.getBrowserSecurityHeaders() != null) {
961  realm.setBrowserSecurityHeaders(rep.getBrowserSecurityHeaders());
962  }
963 
964  if (rep.isInternationalizationEnabled() != null) {
965  realm.setInternationalizationEnabled(rep.isInternationalizationEnabled());
966  }
967  if (rep.getSupportedLocales() != null) {
968  realm.setSupportedLocales(new HashSet<String>(rep.getSupportedLocales()));
969  }
970  if (rep.getDefaultLocale() != null) {
971  realm.setDefaultLocale(rep.getDefaultLocale());
972  }
973  if (rep.getBrowserFlow() != null) {
974  realm.setBrowserFlow(realm.getFlowByAlias(rep.getBrowserFlow()));
975  }
976  if (rep.getRegistrationFlow() != null) {
977  realm.setRegistrationFlow(realm.getFlowByAlias(rep.getRegistrationFlow()));
978  }
979  if (rep.getDirectGrantFlow() != null) {
980  realm.setDirectGrantFlow(realm.getFlowByAlias(rep.getDirectGrantFlow()));
981  }
982  if (rep.getResetCredentialsFlow() != null) {
983  realm.setResetCredentialsFlow(realm.getFlowByAlias(rep.getResetCredentialsFlow()));
984  }
985  if (rep.getClientAuthenticationFlow() != null) {
986  realm.setClientAuthenticationFlow(realm.getFlowByAlias(rep.getClientAuthenticationFlow()));
987  }
988  if (rep.getDockerAuthenticationFlow() != null) {
989  realm.setDockerAuthenticationFlow(realm.getFlowByAlias(rep.getDockerAuthenticationFlow()));
990  }
991  }
static void renameRealm(RealmModel realm, String name)
Definition: RepresentationToModel.java:820
static OTPPolicy toPolicy(RealmRepresentation rep)
Definition: RepresentationToModel.java:135

◆ updateResources()

static void org.keycloak.models.utils.RepresentationToModel.updateResources ( Set< String >  resourceIds,
Policy  policy,
StoreFactory  storeFactory 
)
inlinestaticprivate
2276  {
2277  if (resourceIds != null) {
2278  if (resourceIds.isEmpty()) {
2279  for (Resource resource : new HashSet<>(policy.getResources())) {
2280  policy.removeResource(resource);
2281  }
2282  }
2283  for (String resourceId : resourceIds) {
2284  boolean hasResource = false;
2285  for (Resource resourceModel : new HashSet<>(policy.getResources())) {
2286  if (resourceModel.getId().equals(resourceId) || resourceModel.getName().equals(resourceId)) {
2287  hasResource = true;
2288  }
2289  }
2290  if (!hasResource && !"".equals(resourceId)) {
2291  Resource resource = storeFactory.getResourceStore().findById(resourceId, policy.getResourceServer().getId());
2292 
2293  if (resource == null) {
2294  resource = storeFactory.getResourceStore().findByName(resourceId, policy.getResourceServer().getId());
2295  if (resource == null) {
2296  throw new RuntimeException("Resource with id or name [" + resourceId + "] does not exist or is not owned by the resource server");
2297  }
2298  }
2299 
2300  policy.addResource(resource);
2301  }
2302  }
2303 
2304  for (Resource resourceModel : new HashSet<>(policy.getResources())) {
2305  boolean hasResource = false;
2306 
2307  for (String resourceId : resourceIds) {
2308  if (resourceModel.getId().equals(resourceId) || resourceModel.getName().equals(resourceId)) {
2309  hasResource = true;
2310  }
2311  }
2312 
2313  if (!hasResource) {
2314  policy.removeResource(resourceModel);
2315  }
2316  }
2317  }
2318 
2319  policy.removeConfig("resources");
2320  }

◆ updateScopes()

static void org.keycloak.models.utils.RepresentationToModel.updateScopes ( Set< String >  scopeIds,
Policy  policy,
StoreFactory  storeFactory 
)
inlinestaticprivate
2175  {
2176  if (scopeIds != null) {
2177  if (scopeIds.isEmpty()) {
2178  for (Scope scope : new HashSet<Scope>(policy.getScopes())) {
2179  policy.removeScope(scope);
2180  }
2181  return;
2182  }
2183  for (String scopeId : scopeIds) {
2184  boolean hasScope = false;
2185 
2186  for (Scope scopeModel : new HashSet<Scope>(policy.getScopes())) {
2187  if (scopeModel.getId().equals(scopeId) || scopeModel.getName().equals(scopeId)) {
2188  hasScope = true;
2189  }
2190  }
2191  if (!hasScope) {
2192  ResourceServer resourceServer = policy.getResourceServer();
2193  Scope scope = storeFactory.getScopeStore().findById(scopeId, resourceServer.getId());
2194 
2195  if (scope == null) {
2196  scope = storeFactory.getScopeStore().findByName(scopeId, resourceServer.getId());
2197  if (scope == null) {
2198  throw new RuntimeException("Scope with id or name [" + scopeId + "] does not exist");
2199  }
2200  }
2201 
2202  policy.addScope(scope);
2203  }
2204  }
2205 
2206  for (Scope scopeModel : new HashSet<Scope>(policy.getScopes())) {
2207  boolean hasScope = false;
2208 
2209  for (String scopeId : scopeIds) {
2210  if (scopeModel.getId().equals(scopeId) || scopeModel.getName().equals(scopeId)) {
2211  hasScope = true;
2212  }
2213  }
2214  if (!hasScope) {
2215  policy.removeScope(scopeModel);
2216  }
2217  }
2218  }
2219 
2220  policy.removeConfig("scopes");
2221  }

メンバ詳解

◆ logger

Logger org.keycloak.models.utils.RepresentationToModel.logger = Logger.getLogger(RepresentationToModel.class)
staticprivate

◆ OIDC

final String org.keycloak.models.utils.RepresentationToModel.OIDC = "openid-connect"
static

このクラス詳解は次のファイルから抽出されました: