use of org.keycloak.adapters.saml.SamlDeployment in project keycloak by keycloak.
the class KeycloakConfigurationServletListener method contextInitialized.
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext = sce.getServletContext();
String configResolverClass = servletContext.getInitParameter("keycloak.config.resolver");
SamlDeploymentContext deploymentContext = (SamlDeploymentContext) servletContext.getAttribute(SamlDeployment.class.getName());
if (deploymentContext == null) {
if (configResolverClass != null) {
try {
SamlConfigResolver configResolver = (SamlConfigResolver) servletContext.getClassLoader().loadClass(configResolverClass).newInstance();
deploymentContext = new SamlDeploymentContext(configResolver);
log.infov("Using {0} to resolve Keycloak configuration on a per-request basis.", configResolverClass);
} catch (Exception ex) {
log.errorv("The specified resolver {0} could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: {1}", new Object[] { configResolverClass, ex.getMessage() });
deploymentContext = new SamlDeploymentContext(new DefaultSamlDeployment());
}
} else {
InputStream is = getConfigInputStream(servletContext);
final SamlDeployment deployment;
if (is == null) {
log.warn("No adapter configuration. Keycloak is unconfigured and will deny all requests.");
deployment = new DefaultSamlDeployment();
} else {
try {
ResourceLoader loader = new ResourceLoader() {
@Override
public InputStream getResourceAsStream(String resource) {
return servletContext.getResourceAsStream(resource);
}
};
deployment = new DeploymentBuilder().build(is, loader);
} catch (ParsingException e) {
throw new RuntimeException(e);
}
}
deploymentContext = new SamlDeploymentContext(deployment);
log.debug("Keycloak is using a per-deployment configuration.");
}
}
addTokenStoreUpdaters(servletContext);
servletContext.setAttribute(ADAPTER_DEPLOYMENT_CONTEXT_ATTRIBUTE, deploymentContext);
servletContext.setAttribute(ADAPTER_DEPLOYMENT_CONTEXT_ATTRIBUTE_ELYTRON, deploymentContext);
servletContext.setAttribute(ADAPTER_SESSION_ID_MAPPER_ATTRIBUTE_ELYTRON, idMapper);
servletContext.setAttribute(ADAPTER_SESSION_ID_MAPPER_UPDATER_ATTRIBUTE_ELYTRON, idMapperUpdater);
}
use of org.keycloak.adapters.saml.SamlDeployment in project keycloak by keycloak.
the class AbstractSamlAuthMech method registerNotifications.
protected void registerNotifications(final SecurityContext securityContext) {
final NotificationReceiver logoutReceiver = new NotificationReceiver() {
@Override
public void handleNotification(SecurityNotification notification) {
if (notification.getEventType() != SecurityNotification.EventType.LOGGED_OUT)
return;
HttpServerExchange exchange = notification.getExchange();
UndertowHttpFacade facade = createFacade(exchange);
SamlDeployment deployment = deploymentContext.resolveDeployment(facade);
SamlSessionStore sessionStore = getTokenStore(exchange, facade, deployment, securityContext);
sessionStore.logoutAccount();
}
};
securityContext.registerNotificationReceiver(logoutReceiver);
}
use of org.keycloak.adapters.saml.SamlDeployment in project keycloak by keycloak.
the class AbstractSamlAuthenticator method initializeKeycloak.
@SuppressWarnings("UseSpecificCatch")
public void initializeKeycloak() {
ServletContext theServletContext = null;
ContextHandler.Context currentContext = ContextHandler.getCurrentContext();
if (currentContext != null) {
String contextPath = currentContext.getContextPath();
if ("".equals(contextPath)) {
// This could be the case in osgi environment when deploying apps through pax whiteboard extension.
theServletContext = currentContext;
} else {
theServletContext = currentContext.getContext(contextPath);
}
}
// Jetty 9.1.x servlet context will be null :(
if (configResolver == null && theServletContext != null) {
String configResolverClass = theServletContext.getInitParameter("keycloak.config.resolver");
if (configResolverClass != null) {
try {
configResolver = (SamlConfigResolver) ContextHandler.getCurrentContext().getClassLoader().loadClass(configResolverClass).newInstance();
log.infov("Using {0} to resolve Keycloak configuration on a per-request basis.", configResolverClass);
} catch (Exception ex) {
log.infov("The specified resolver {0} could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: {1}", new Object[] { configResolverClass, ex.getMessage() });
}
}
}
if (configResolver != null) {
// deploymentContext = new AdapterDeploymentContext(configResolver);
} else if (theServletContext != null) {
InputStream configInputStream = getConfigInputStream(theServletContext);
if (configInputStream != null) {
final ServletContext servletContext = theServletContext;
SamlDeployment deployment = null;
try {
deployment = new DeploymentBuilder().build(configInputStream, new ResourceLoader() {
@Override
public InputStream getResourceAsStream(String resource) {
return servletContext.getResourceAsStream(resource);
}
});
} catch (ParsingException e) {
throw new RuntimeException(e);
}
deploymentContext = new SamlDeploymentContext(deployment);
}
}
if (theServletContext != null)
theServletContext.setAttribute(SamlDeploymentContext.class.getName(), deploymentContext);
}
use of org.keycloak.adapters.saml.SamlDeployment in project keycloak by keycloak.
the class DeploymentBuilder method build.
public SamlDeployment build(InputStream xml, ResourceLoader resourceLoader) throws ParsingException {
DefaultSamlDeployment deployment = new DefaultSamlDeployment();
DefaultSamlDeployment.DefaultIDP defaultIDP = new DefaultSamlDeployment.DefaultIDP();
DefaultSamlDeployment.DefaultSingleSignOnService sso = new DefaultSamlDeployment.DefaultSingleSignOnService();
DefaultSamlDeployment.DefaultSingleLogoutService slo = new DefaultSamlDeployment.DefaultSingleLogoutService();
defaultIDP.setSingleSignOnService(sso);
defaultIDP.setSingleLogoutService(slo);
KeycloakSamlAdapter adapter = (KeycloakSamlAdapter) KeycloakSamlAdapterParser.getInstance().parse(xml);
SP sp = adapter.getSps().get(0);
deployment.setConfigured(true);
deployment.setEntityID(sp.getEntityID());
try {
URI.create(sp.getEntityID());
} catch (IllegalArgumentException ex) {
log.warnf("Entity ID is not an URI, assertion that restricts audience will fail. Update Entity ID to be URI.", sp.getEntityID());
}
deployment.setForceAuthentication(sp.isForceAuthentication());
deployment.setIsPassive(sp.isIsPassive());
deployment.setNameIDPolicyFormat(sp.getNameIDPolicyFormat());
deployment.setLogoutPage(sp.getLogoutPage());
IDP idp = sp.getIdp();
deployment.setSignatureCanonicalizationMethod(idp.getSignatureCanonicalizationMethod());
deployment.setAutodetectBearerOnly(sp.isAutodetectBearerOnly());
deployment.setKeepDOMAssertion(sp.isKeepDOMAssertion());
deployment.setSignatureAlgorithm(SignatureAlgorithm.RSA_SHA256);
if (idp.getSignatureAlgorithm() != null) {
deployment.setSignatureAlgorithm(SignatureAlgorithm.valueOf(idp.getSignatureAlgorithm()));
}
if (sp.getPrincipalNameMapping() != null) {
SamlDeployment.PrincipalNamePolicy policy = SamlDeployment.PrincipalNamePolicy.valueOf(sp.getPrincipalNameMapping().getPolicy());
deployment.setPrincipalNamePolicy(policy);
deployment.setPrincipalAttributeName(sp.getPrincipalNameMapping().getAttributeName());
}
deployment.setRoleAttributeNames(sp.getRoleAttributes());
if (sp.getRoleAttributes() == null) {
Set<String> roles = new HashSet<>();
roles.add("Role");
deployment.setRoleAttributeNames(roles);
}
if (sp.getSslPolicy() != null) {
SslRequired ssl = SslRequired.valueOf(sp.getSslPolicy());
deployment.setSslRequired(ssl);
}
if (sp.getKeys() != null) {
for (Key key : sp.getKeys()) {
if (key.isSigning()) {
PrivateKey privateKey = null;
PublicKey publicKey = null;
if (key.getKeystore() != null) {
KeyStore keyStore = loadKeystore(resourceLoader, key);
Certificate cert = null;
try {
log.debugf("Try to load key [%s]", key.getKeystore().getCertificateAlias());
cert = keyStore.getCertificate(key.getKeystore().getCertificateAlias());
if (cert == null) {
log.errorf("Key alias %s is not found into keystore", key.getKeystore().getCertificateAlias());
}
privateKey = (PrivateKey) keyStore.getKey(key.getKeystore().getPrivateKeyAlias(), key.getKeystore().getPrivateKeyPassword().toCharArray());
publicKey = cert.getPublicKey();
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
if (key.getPrivateKeyPem() == null) {
throw new RuntimeException("SP signing key must have a PrivateKey defined");
}
try {
privateKey = PemUtils.decodePrivateKey(key.getPrivateKeyPem().trim());
if (key.getPublicKeyPem() == null && key.getCertificatePem() == null) {
throw new RuntimeException("Sp signing key must have a PublicKey or Certificate defined");
}
publicKey = getPublicKeyFromPem(key);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
KeyPair keyPair = new KeyPair(publicKey, privateKey);
deployment.setSigningKeyPair(keyPair);
}
if (key.isEncryption()) {
if (key.getKeystore() != null) {
KeyStore keyStore = loadKeystore(resourceLoader, key);
try {
PrivateKey privateKey = (PrivateKey) keyStore.getKey(key.getKeystore().getPrivateKeyAlias(), key.getKeystore().getPrivateKeyPassword().toCharArray());
deployment.setDecryptionKey(privateKey);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
if (key.getPrivateKeyPem() == null) {
throw new RuntimeException("SP signing key must have a PrivateKey defined");
}
try {
PrivateKey privateKey = PemUtils.decodePrivateKey(key.getPrivateKeyPem().trim());
deployment.setDecryptionKey(privateKey);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
}
deployment.setIdp(defaultIDP);
defaultIDP.setEntityID(idp.getEntityID());
sso.setRequestBinding(SamlDeployment.Binding.parseBinding(idp.getSingleSignOnService().getRequestBinding()));
sso.setRequestBindingUrl(idp.getSingleSignOnService().getBindingUrl());
if (idp.getSingleSignOnService().getResponseBinding() != null) {
sso.setResponseBinding(SamlDeployment.Binding.parseBinding(idp.getSingleSignOnService().getResponseBinding()));
}
if (idp.getAllowedClockSkew() != null) {
defaultIDP.setAllowedClockSkew(convertClockSkewInMillis(idp.getAllowedClockSkew(), idp.getAllowedClockSkewUnit()));
}
if (idp.getSingleSignOnService().getAssertionConsumerServiceUrl() != null) {
if (!idp.getSingleSignOnService().getAssertionConsumerServiceUrl().endsWith("/saml")) {
throw new RuntimeException("AssertionConsumerServiceUrl must end with \"/saml\".");
}
sso.setAssertionConsumerServiceUrl(URI.create(idp.getSingleSignOnService().getAssertionConsumerServiceUrl()));
}
sso.setSignRequest(idp.getSingleSignOnService().isSignRequest());
sso.setValidateResponseSignature(idp.getSingleSignOnService().isValidateResponseSignature());
sso.setValidateAssertionSignature(idp.getSingleSignOnService().isValidateAssertionSignature());
slo.setSignRequest(idp.getSingleLogoutService().isSignRequest());
slo.setSignResponse(idp.getSingleLogoutService().isSignResponse());
slo.setValidateResponseSignature(idp.getSingleLogoutService().isValidateResponseSignature());
slo.setValidateRequestSignature(idp.getSingleLogoutService().isValidateRequestSignature());
slo.setRequestBinding(SamlDeployment.Binding.parseBinding(idp.getSingleLogoutService().getRequestBinding()));
slo.setResponseBinding(SamlDeployment.Binding.parseBinding(idp.getSingleLogoutService().getResponseBinding()));
if (slo.getRequestBinding() == SamlDeployment.Binding.POST) {
slo.setRequestBindingUrl(idp.getSingleLogoutService().getPostBindingUrl());
} else {
slo.setRequestBindingUrl(idp.getSingleLogoutService().getRedirectBindingUrl());
}
if (slo.getResponseBinding() == SamlDeployment.Binding.POST) {
slo.setResponseBindingUrl(idp.getSingleLogoutService().getPostBindingUrl());
} else {
slo.setResponseBindingUrl(idp.getSingleLogoutService().getRedirectBindingUrl());
}
if (idp.getKeys() != null) {
for (Key key : idp.getKeys()) {
if (key.isSigning()) {
processSigningKey(defaultIDP, key, resourceLoader);
}
}
}
defaultIDP.setMetadataUrl(idp.getMetadataUrl());
defaultIDP.setClient(new HttpClientBuilder().build(idp.getHttpClientConfig()));
defaultIDP.refreshKeyLocatorConfiguration();
// set the role mappings provider.
deployment.setRoleMappingsProvider(RoleMappingsProviderUtils.bootstrapRoleMappingsProvider(deployment, resourceLoader, sp.getRoleMappingsProviderConfig()));
return deployment;
}
use of org.keycloak.adapters.saml.SamlDeployment in project keycloak by keycloak.
the class ArtifactBindingTest method testArtifactBindingLoginSignedArtifactResponse.
@Test
public void testArtifactBindingLoginSignedArtifactResponse() throws Exception {
getCleanup().addCleanup(ClientAttributeUpdater.forClient(adminClient, REALM_NAME, SAML_CLIENT_ID_SALES_POST).setAttribute(SamlConfigAttributes.SAML_ARTIFACT_BINDING, "true").setAttribute(SamlConfigAttributes.SAML_SERVER_SIGNATURE, "true").update());
SAMLDocumentHolder response = new SamlClientBuilder().authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, SAML_ASSERTION_CONSUMER_URL_SALES_POST, SamlClient.Binding.POST).build().login().user(bburkeUser).build().handleArtifact(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST).build().doNotFollowRedirects().executeAndTransform(this::getArtifactResponse);
assertThat(response.getSamlObject(), instanceOf(ArtifactResponseType.class));
ArtifactResponseType artifactResponse = (ArtifactResponseType) response.getSamlObject();
assertThat(artifactResponse, isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
assertThat(artifactResponse.getSignature(), notNullValue());
assertThat(artifactResponse.getAny(), instanceOf(ResponseType.class));
assertThat(artifactResponse.getInResponseTo(), not(isEmptyOrNullString()));
ResponseType samlResponse = (ResponseType) artifactResponse.getAny();
assertThat(samlResponse, isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
SamlDeployment deployment = SamlUtils.getSamlDeploymentForClient("sales-post");
SamlProtocolUtils.verifyDocumentSignature(response.getSamlDocument(), deployment.getIDP().getSignatureValidationKeyLocator());
}
Aggregations