use of org.keycloak.Config in project keycloak by keycloak.
the class ClientPolicyProviderFactory method onExport.
@Override
public void onExport(Policy policy, PolicyRepresentation representation, AuthorizationProvider authorization) {
ClientPolicyRepresentation userRep = toRepresentation(policy, authorization);
Map<String, String> config = new HashMap<>();
try {
RealmModel realm = authorization.getRealm();
config.put("clients", JsonSerialization.writeValueAsString(userRep.getClients().stream().map(id -> realm.getClientById(id).getClientId()).collect(Collectors.toList())));
} catch (IOException cause) {
throw new RuntimeException("Failed to export user policy [" + policy.getName() + "]", cause);
}
representation.setConfig(config);
}
use of org.keycloak.Config in project keycloak by keycloak.
the class EntityDescriptorDescriptionConverter method loadEntityDescriptors.
private static ClientRepresentation loadEntityDescriptors(InputStream is) {
Object metadata;
try {
metadata = SAMLParser.getInstance().parse(is);
} catch (ParsingException e) {
throw new RuntimeException(e);
}
EntitiesDescriptorType entities;
if (EntitiesDescriptorType.class.isInstance(metadata)) {
entities = (EntitiesDescriptorType) metadata;
} else {
entities = new EntitiesDescriptorType();
entities.addEntityDescriptor(metadata);
}
if (entities.getEntityDescriptor().size() != 1) {
throw new RuntimeException("Expected one entity descriptor");
}
EntityDescriptorType entity = (EntityDescriptorType) entities.getEntityDescriptor().get(0);
String entityId = entity.getEntityID();
ClientRepresentation app = new ClientRepresentation();
app.setClientId(entityId);
Map<String, String> attributes = new HashMap<>();
app.setAttributes(attributes);
List<String> redirectUris = new LinkedList<>();
app.setRedirectUris(redirectUris);
app.setFullScopeAllowed(true);
app.setProtocol(SamlProtocol.LOGIN_PROTOCOL);
// default to true
attributes.put(SamlConfigAttributes.SAML_SERVER_SIGNATURE, SamlProtocol.ATTRIBUTE_TRUE_VALUE);
// default to false
attributes.put(SamlConfigAttributes.SAML_SERVER_SIGNATURE_KEYINFO_EXT, SamlProtocol.ATTRIBUTE_FALSE_VALUE);
attributes.put(SamlConfigAttributes.SAML_SIGNATURE_ALGORITHM, SignatureAlgorithm.RSA_SHA256.toString());
attributes.put(SamlConfigAttributes.SAML_AUTHNSTATEMENT, SamlProtocol.ATTRIBUTE_TRUE_VALUE);
SPSSODescriptorType spDescriptorType = getSPDescriptor(entity);
if (spDescriptorType.isWantAssertionsSigned()) {
attributes.put(SamlConfigAttributes.SAML_ASSERTION_SIGNATURE, SamlProtocol.ATTRIBUTE_TRUE_VALUE);
}
String logoutPost = getLogoutLocation(spDescriptorType, JBossSAMLURIConstants.SAML_HTTP_POST_BINDING.get());
if (logoutPost != null)
attributes.put(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_POST_ATTRIBUTE, logoutPost);
String logoutRedirect = getLogoutLocation(spDescriptorType, JBossSAMLURIConstants.SAML_HTTP_REDIRECT_BINDING.get());
if (logoutRedirect != null)
attributes.put(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_REDIRECT_ATTRIBUTE, logoutRedirect);
String assertionConsumerServicePostBinding = getServiceURL(spDescriptorType, JBossSAMLURIConstants.SAML_HTTP_POST_BINDING.get());
if (assertionConsumerServicePostBinding != null) {
attributes.put(SamlProtocol.SAML_ASSERTION_CONSUMER_URL_POST_ATTRIBUTE, assertionConsumerServicePostBinding);
redirectUris.add(assertionConsumerServicePostBinding);
}
String assertionConsumerServiceRedirectBinding = getServiceURL(spDescriptorType, JBossSAMLURIConstants.SAML_HTTP_REDIRECT_BINDING.get());
if (assertionConsumerServiceRedirectBinding != null) {
attributes.put(SamlProtocol.SAML_ASSERTION_CONSUMER_URL_REDIRECT_ATTRIBUTE, assertionConsumerServiceRedirectBinding);
redirectUris.add(assertionConsumerServiceRedirectBinding);
}
String assertionConsumerServiceSoapBinding = getServiceURL(spDescriptorType, JBossSAMLURIConstants.SAML_SOAP_BINDING.get());
if (assertionConsumerServiceSoapBinding != null) {
redirectUris.add(assertionConsumerServiceSoapBinding);
}
String assertionConsumerServicePaosBinding = getServiceURL(spDescriptorType, JBossSAMLURIConstants.SAML_PAOS_BINDING.get());
if (assertionConsumerServicePaosBinding != null) {
redirectUris.add(assertionConsumerServicePaosBinding);
}
String assertionConsumerServiceArtifactBinding = getServiceURL(spDescriptorType, JBossSAMLURIConstants.SAML_HTTP_ARTIFACT_BINDING.get());
if (assertionConsumerServiceArtifactBinding != null) {
attributes.put(SamlProtocol.SAML_ASSERTION_CONSUMER_URL_ARTIFACT_ATTRIBUTE, assertionConsumerServiceArtifactBinding);
redirectUris.add(assertionConsumerServiceArtifactBinding);
}
String artifactResolutionService = getArtifactResolutionService(spDescriptorType);
if (artifactResolutionService != null) {
attributes.put(SamlProtocol.SAML_ARTIFACT_RESOLUTION_SERVICE_URL_ATTRIBUTE, artifactResolutionService);
}
if (spDescriptorType.getNameIDFormat() != null) {
for (String format : spDescriptorType.getNameIDFormat()) {
String attribute = SamlClient.samlNameIDFormatToClientAttribute(format);
if (attribute != null) {
attributes.put(SamlConfigAttributes.SAML_NAME_ID_FORMAT_ATTRIBUTE, attribute);
break;
}
}
}
if (spDescriptorType.getExtensions() != null && spDescriptorType.getExtensions().getUIInfo() != null) {
if (!spDescriptorType.getExtensions().getUIInfo().getLogo().isEmpty()) {
attributes.put(ClientModel.LOGO_URI, spDescriptorType.getExtensions().getUIInfo().getLogo().get(0).getValue().toString());
}
if (!spDescriptorType.getExtensions().getUIInfo().getPrivacyStatementURL().isEmpty()) {
attributes.put(ClientModel.POLICY_URI, spDescriptorType.getExtensions().getUIInfo().getPrivacyStatementURL().stream().filter(dn -> "en".equals(dn.getLang())).findFirst().orElse(spDescriptorType.getExtensions().getUIInfo().getPrivacyStatementURL().get(0)).getValue().toString());
}
}
app.setProtocolMappers(spDescriptorType.getAttributeConsumingService().stream().flatMap(att -> att.getRequestedAttribute().stream()).map(attr -> {
ProtocolMapperRepresentation mapper = new ProtocolMapperRepresentation();
mapper.setName(attr.getName());
mapper.setProtocol("saml");
mapper.setProtocolMapper(UserAttributeStatementMapper.PROVIDER_ID);
Map<String, String> config = new HashMap<>();
config.put(AttributeStatementHelper.SAML_ATTRIBUTE_NAME, attr.getName());
if (attr.getFriendlyName() != null)
config.put(AttributeStatementHelper.FRIENDLY_NAME, attr.getFriendlyName());
if (attr.getNameFormat() != null)
config.put(AttributeStatementHelper.SAML_ATTRIBUTE_NAMEFORMAT, getSAMLNameFormat(attr.getNameFormat()));
mapper.setConfig(config);
return mapper;
}).collect(Collectors.toList()));
for (KeyDescriptorType keyDescriptor : spDescriptorType.getKeyDescriptor()) {
X509Certificate cert = null;
try {
cert = SAMLMetadataUtil.getCertificate(keyDescriptor);
} catch (ConfigurationException e) {
throw new RuntimeException(e);
} catch (ProcessingException e) {
throw new RuntimeException(e);
}
String certPem = KeycloakModelUtils.getPemFromCertificate(cert);
if (keyDescriptor.getUse() == KeyTypes.SIGNING) {
attributes.put(SamlConfigAttributes.SAML_CLIENT_SIGNATURE_ATTRIBUTE, SamlProtocol.ATTRIBUTE_TRUE_VALUE);
attributes.put(SamlConfigAttributes.SAML_SIGNING_CERTIFICATE_ATTRIBUTE, certPem);
} else if (keyDescriptor.getUse() == KeyTypes.ENCRYPTION) {
attributes.put(SamlConfigAttributes.SAML_ENCRYPT, SamlProtocol.ATTRIBUTE_TRUE_VALUE);
attributes.put(SamlConfigAttributes.SAML_ENCRYPTION_CERTIFICATE_ATTRIBUTE, certPem);
}
}
return app;
}
use of org.keycloak.Config in project keycloak by keycloak.
the class GroupPolicyProviderFactory method updatePolicy.
private void updatePolicy(Policy policy, String groupsClaim, Set<GroupPolicyRepresentation.GroupDefinition> groups, AuthorizationProvider authorization) {
if (groups == null || groups.isEmpty()) {
throw new RuntimeException("You must provide at least one group");
}
Map<String, String> config = new HashMap<>(policy.getConfig());
if (groupsClaim != null) {
config.put("groupsClaim", groupsClaim);
}
List<GroupModel> topLevelGroups = authorization.getRealm().getTopLevelGroupsStream().collect(Collectors.toList());
for (GroupPolicyRepresentation.GroupDefinition definition : groups) {
GroupModel group = null;
if (definition.getId() != null) {
group = authorization.getRealm().getGroupById(definition.getId());
}
String path = definition.getPath();
if (group == null && path != null) {
String canonicalPath = path.startsWith("/") ? path.substring(1, path.length()) : path;
if (canonicalPath != null) {
String[] parts = canonicalPath.split("/");
GroupModel parent = null;
for (String part : parts) {
if (parent == null) {
parent = topLevelGroups.stream().filter(groupModel -> groupModel.getName().equals(part)).findFirst().orElseThrow(() -> new RuntimeException("Top level group with name [" + part + "] not found"));
} else {
group = parent.getSubGroupsStream().filter(groupModel -> groupModel.getName().equals(part)).findFirst().orElseThrow(() -> new RuntimeException("Group with name [" + part + "] not found"));
parent = group;
}
}
if (parts.length == 1) {
group = parent;
}
}
}
if (group == null) {
throw new RuntimeException("Group with id [" + definition.getId() + "] not found");
}
definition.setId(group.getId());
definition.setPath(null);
}
try {
config.put("groups", JsonSerialization.writeValueAsString(groups));
} catch (IOException cause) {
throw new RuntimeException("Failed to serialize groups", cause);
}
policy.setConfig(config);
}
use of org.keycloak.Config in project keycloak by keycloak.
the class UserPolicyProviderFactory method onExport.
@Override
public void onExport(Policy policy, PolicyRepresentation representation, AuthorizationProvider authorizationProvider) {
UserPolicyRepresentation userRep = toRepresentation(policy, authorizationProvider);
Map<String, String> config = new HashMap<>();
try {
UserProvider userProvider = authorizationProvider.getKeycloakSession().users();
RealmModel realm = authorizationProvider.getRealm();
config.put("users", JsonSerialization.writeValueAsString(userRep.getUsers().stream().map(id -> userProvider.getUserById(realm, id).getUsername()).collect(Collectors.toList())));
} catch (IOException cause) {
throw new RuntimeException("Failed to export user policy [" + policy.getName() + "]", cause);
}
representation.setConfig(config);
}
use of org.keycloak.Config in project keycloak by keycloak.
the class RemoteCacheProvider method getOrCreateSecuredRemoteCacheManager.
protected RemoteCacheManager getOrCreateSecuredRemoteCacheManager(Config.Scope config, String cacheName, RemoteCacheManager origManager) {
String serverName = config.get("remoteStoreSecurityServerName", "keycloak-jdg-server");
String realm = config.get("remoteStoreSecurityRealm", "AllowScriptManager");
String username = config.get("remoteStoreSecurityUsername", "___script_manager");
String password = config.get("remoteStoreSecurityPassword", "not-so-secret-password");
// Create configuration template from the original configuration provided at remoteStore level
Configuration origConfig = origManager.getConfiguration();
ConfigurationBuilder cfgBuilder = new ConfigurationBuilder().read(origConfig);
String securedHotRodEndpoint = origConfig.servers().stream().map(serverConfiguration -> serverConfiguration.host() + ":" + serverConfiguration.port()).collect(Collectors.joining(";"));
if (managedManagers.containsKey(securedHotRodEndpoint)) {
return managedManagers.get(securedHotRodEndpoint);
}
logger.infof("Creating secured RemoteCacheManager for Server: '%s', Cache: '%s', Realm: '%s', Username: '%s', Secured HotRod endpoint: '%s'", serverName, cacheName, realm, username, securedHotRodEndpoint);
// Workaround as I need a way to override servers and it's not possible to remove existing :/
try {
Field serversField = cfgBuilder.getClass().getDeclaredField("servers");
Reflections.setAccessible(serversField);
List origServers = Reflections.getFieldValue(serversField, cfgBuilder, List.class);
origServers.clear();
} catch (NoSuchFieldException nsfe) {
throw new RuntimeException(nsfe);
}
// Create configuration based on the configuration template from remoteStore. Just add security and override secured endpoint
Configuration newConfig = cfgBuilder.addServers(securedHotRodEndpoint).security().authentication().serverName(// define server name, should be specified in XML configuration on JDG side
serverName).saslMechanism(// define SASL mechanism, in this example we use DIGEST with MD5 hash
"DIGEST-MD5").callbackHandler(// define login handler, implementation defined
new LoginHandler(username, password.toCharArray(), realm)).enable().build();
final RemoteCacheManager remoteCacheManager = new RemoteCacheManager(newConfig);
managedManagers.put(securedHotRodEndpoint, remoteCacheManager);
return remoteCacheManager;
}
Aggregations