use of io.undertow.server.HttpHandler in project undertow by undertow-io.
the class ModClusterTestSetup method main.
public static void main(final String[] args) throws IOException {
final Undertow server;
final XnioWorker worker = Xnio.getInstance().createWorker(OptionMap.EMPTY);
final ModCluster modCluster = ModCluster.builder(worker).setHealthCheckInterval(TimeUnit.SECONDS.toMillis(3)).setRemoveBrokenNodes(TimeUnit.SECONDS.toMillis(30)).build();
try {
if (chost == null) {
// We are going to guess it.
chost = java.net.InetAddress.getLocalHost().getHostName();
System.out.println("Using: " + chost + ":" + cport);
}
modCluster.start();
// Create the proxy and mgmt handler
final HttpHandler proxy = modCluster.createProxyHandler();
final MCMPConfig config = MCMPConfig.builder().setManagementHost(chost).setManagementPort(cport).enableAdvertise().setSecurityKey("secret").getParent().build();
final MCMPConfig webConfig = MCMPConfig.webBuilder().setManagementHost(chost).setManagementPort(cport).build();
// Setup specific rewrite rules for the mod_cluster tests.
final HttpHandler root = Handlers.predicates(PredicatedHandlersParser.parse("regex[pattern='cluster.domain.com', value='%{i,Host}'] and equals[%R, '/'] -> rewrite['/myapp/MyCount']\n" + "regex[pattern='cluster.domain.org', value='%{i,Host}'] and regex['/(.*)'] -> rewrite['/myapp/${1}']\n" + "regex[pattern='cluster.domain.net', value='%{i,Host}'] and regex['/test/(.*)'] -> rewrite['/myapp/${1}']\n" + "regex[pattern='cluster.domain.info', value='%{i,Host}'] and path-template['/{one}/{two}'] -> rewrite['/test/${two}?partnerpath=/${one}&%q']\n", ModClusterTestSetup.class.getClassLoader()), proxy);
final HttpHandler mcmp = config.create(modCluster, root);
final HttpHandler web = webConfig.create(modCluster, ResponseCodeHandler.HANDLE_404);
server = Undertow.builder().addHttpListener(cport, chost).addHttpListener(pport, phost).setHandler(Handlers.path(mcmp).addPrefixPath("/mod_cluster_manager", web)).build();
server.start();
// Start advertising the mcmp handler
modCluster.advertise(config);
final Runnable r = new Runnable() {
@Override
public void run() {
modCluster.stop();
server.stop();
}
};
Runtime.getRuntime().addShutdownHook(new Thread(r));
} catch (Exception e) {
e.printStackTrace();
}
}
use of io.undertow.server.HttpHandler in project undertow by undertow-io.
the class InMemorySessionTestCase method inMemoryMaxSessionsTest.
@Test
public void inMemoryMaxSessionsTest() throws IOException {
TestHttpClient client1 = new TestHttpClient();
client1.setCookieStore(new BasicCookieStore());
TestHttpClient client2 = new TestHttpClient();
client2.setCookieStore(new BasicCookieStore());
try {
final SessionCookieConfig sessionConfig = new SessionCookieConfig();
final SessionAttachmentHandler handler = new SessionAttachmentHandler(new InMemorySessionManager("", 1, true), sessionConfig);
handler.setNext(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final SessionManager manager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
Session session = manager.getSession(exchange, sessionConfig);
if (session == null) {
session = manager.createSession(exchange, sessionConfig);
session.setAttribute(COUNT, 0);
}
Integer count = (Integer) session.getAttribute(COUNT);
exchange.getResponseHeaders().add(new HttpString(COUNT), count.toString());
session.setAttribute(COUNT, ++count);
}
});
DefaultServer.setRootHandler(handler);
HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
HttpResponse result = client1.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
Header[] header = result.getHeaders(COUNT);
Assert.assertEquals("0", header[0].getValue());
get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
result = client1.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
header = result.getHeaders(COUNT);
Assert.assertEquals("1", header[0].getValue());
get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
result = client2.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
header = result.getHeaders(COUNT);
Assert.assertEquals("0", header[0].getValue());
get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
result = client1.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
header = result.getHeaders(COUNT);
Assert.assertEquals("0", header[0].getValue());
} finally {
client1.getConnectionManager().shutdown();
client2.getConnectionManager().shutdown();
}
}
use of io.undertow.server.HttpHandler in project undertow by undertow-io.
the class DeploymentManagerImpl method setupSecurityHandlers.
/**
* sets up the outer security handlers.
* <p/>
* the handler that actually performs the access check happens later in the chain, it is not setup here
*
* @param initialHandler The handler to wrap with security handlers
*/
private HttpHandler setupSecurityHandlers(HttpHandler initialHandler) {
final DeploymentInfo deploymentInfo = deployment.getDeploymentInfo();
final LoginConfig loginConfig = deploymentInfo.getLoginConfig();
HttpHandler current = initialHandler;
current = new SSLInformationAssociationHandler(current);
final SecurityPathMatches securityPathMatches = buildSecurityConstraints();
securityPathMatches.logWarningsAboutUncoveredMethods();
current = new ServletAuthenticationCallHandler(current);
for (HandlerWrapper wrapper : deploymentInfo.getSecurityWrappers()) {
current = wrapper.wrap(current);
}
if (deploymentInfo.isDisableCachingForSecuredPages()) {
current = Handlers.predicate(Predicates.authRequired(), Handlers.disableCache(current), current);
}
if (!securityPathMatches.isEmpty()) {
current = new ServletAuthenticationConstraintHandler(current);
}
current = new ServletConfidentialityConstraintHandler(deploymentInfo.getConfidentialPortManager(), current);
if (!securityPathMatches.isEmpty()) {
current = new ServletSecurityConstraintHandler(securityPathMatches, current);
}
HandlerWrapper initialSecurityWrapper = deploymentInfo.getInitialSecurityWrapper();
String mechName = null;
if (initialSecurityWrapper == null) {
final Map<String, AuthenticationMechanismFactory> factoryMap = new HashMap<>(deploymentInfo.getAuthenticationMechanisms());
final IdentityManager identityManager = deploymentInfo.getIdentityManager();
if (!factoryMap.containsKey(BASIC_AUTH)) {
factoryMap.put(BASIC_AUTH, new BasicAuthenticationMechanism.Factory(identityManager));
}
if (!factoryMap.containsKey(FORM_AUTH)) {
factoryMap.put(FORM_AUTH, new ServletFormAuthenticationMechanism.Factory(identityManager));
}
if (!factoryMap.containsKey(DIGEST_AUTH)) {
factoryMap.put(DIGEST_AUTH, new DigestAuthenticationMechanism.Factory(identityManager));
}
if (!factoryMap.containsKey(CLIENT_CERT_AUTH)) {
factoryMap.put(CLIENT_CERT_AUTH, new ClientCertAuthenticationMechanism.Factory(identityManager));
}
if (!factoryMap.containsKey(ExternalAuthenticationMechanism.NAME)) {
factoryMap.put(ExternalAuthenticationMechanism.NAME, new ExternalAuthenticationMechanism.Factory(identityManager));
}
if (!factoryMap.containsKey(GenericHeaderAuthenticationMechanism.NAME)) {
factoryMap.put(GenericHeaderAuthenticationMechanism.NAME, new GenericHeaderAuthenticationMechanism.Factory(identityManager));
}
List<AuthenticationMechanism> authenticationMechanisms = new LinkedList<>();
if (deploymentInfo.isUseCachedAuthenticationMechanism()) {
authenticationMechanisms.add(new CachedAuthenticatedSessionMechanism(identityManager));
}
if (loginConfig != null || deploymentInfo.getJaspiAuthenticationMechanism() != null) {
//we don't allow multipart requests, and use the default encoding when it's set
FormEncodedDataDefinition formEncodedDataDefinition = new FormEncodedDataDefinition();
if (deploymentInfo.getDefaultEncoding() != null) {
formEncodedDataDefinition.setDefaultEncoding(deploymentInfo.getDefaultEncoding());
}
FormParserFactory parser = FormParserFactory.builder(false).addParser(formEncodedDataDefinition).build();
List<AuthMethodConfig> authMethods = Collections.<AuthMethodConfig>emptyList();
if (loginConfig != null) {
authMethods = loginConfig.getAuthMethods();
}
for (AuthMethodConfig method : authMethods) {
AuthenticationMechanismFactory factory = factoryMap.get(method.getName());
if (factory == null) {
throw UndertowServletMessages.MESSAGES.unknownAuthenticationMechanism(method.getName());
}
if (mechName == null) {
mechName = method.getName();
}
final Map<String, String> properties = new HashMap<>();
properties.put(AuthenticationMechanismFactory.CONTEXT_PATH, deploymentInfo.getContextPath());
properties.put(AuthenticationMechanismFactory.REALM, loginConfig.getRealmName());
properties.put(AuthenticationMechanismFactory.ERROR_PAGE, loginConfig.getErrorPage());
properties.put(AuthenticationMechanismFactory.LOGIN_PAGE, loginConfig.getLoginPage());
properties.putAll(method.getProperties());
String name = method.getName().toUpperCase(Locale.US);
// The mechanism name is passed in from the HttpServletRequest interface as the name reported needs to be
// comparable using '=='
name = name.equals(FORM_AUTH) ? FORM_AUTH : name;
name = name.equals(BASIC_AUTH) ? BASIC_AUTH : name;
name = name.equals(DIGEST_AUTH) ? DIGEST_AUTH : name;
name = name.equals(CLIENT_CERT_AUTH) ? CLIENT_CERT_AUTH : name;
authenticationMechanisms.add(factory.create(name, parser, properties));
}
}
deployment.setAuthenticationMechanisms(authenticationMechanisms);
//if the JASPI auth mechanism is set then it takes over
if (deploymentInfo.getJaspiAuthenticationMechanism() == null) {
current = new AuthenticationMechanismsHandler(current, authenticationMechanisms);
} else {
current = new AuthenticationMechanismsHandler(current, Collections.<AuthenticationMechanism>singletonList(deploymentInfo.getJaspiAuthenticationMechanism()));
}
current = new CachedAuthenticatedSessionHandler(current, this.deployment.getServletContext());
}
List<NotificationReceiver> notificationReceivers = deploymentInfo.getNotificationReceivers();
if (!notificationReceivers.isEmpty()) {
current = new NotificationReceiverHandler(current, notificationReceivers);
}
if (initialSecurityWrapper == null) {
// TODO - A switch to constraint driven could be configurable, however before we can support that with servlets we would
// need additional tracking within sessions if a servlet has specifically requested that authentication occurs.
SecurityContextFactory contextFactory = deploymentInfo.getSecurityContextFactory();
if (contextFactory == null) {
contextFactory = SecurityContextFactoryImpl.INSTANCE;
}
current = new SecurityInitialHandler(deploymentInfo.getAuthenticationMode(), deploymentInfo.getIdentityManager(), mechName, contextFactory, current);
} else {
current = initialSecurityWrapper.wrap(current);
}
return current;
}
use of io.undertow.server.HttpHandler in project undertow by undertow-io.
the class Http2Server method main.
public static void main(final String[] args) throws Exception {
String version = System.getProperty("java.version");
System.out.println("Java version " + version);
if (version.charAt(0) == '1' && Integer.parseInt(version.charAt(2) + "") < 8) {
System.out.println("This example requires Java 1.8 or later");
System.out.println("The HTTP2 spec requires certain cyphers that are not present in older JVM's");
System.out.println("See section 9.2.2 of the HTTP2 specification for details");
System.exit(1);
}
String bindAddress = System.getProperty("bind.address", "localhost");
SSLContext sslContext = createSSLContext(loadKeyStore("server.keystore"), loadKeyStore("server.truststore"));
Undertow server = Undertow.builder().setServerOption(UndertowOptions.ENABLE_HTTP2, true).addHttpListener(8080, bindAddress).addHttpsListener(8443, bindAddress, sslContext).setHandler(new SessionAttachmentHandler(new LearningPushHandler(100, -1, Handlers.header(predicate(secure(), resource(new PathResourceManager(Paths.get(System.getProperty("example.directory", System.getProperty("user.home"))), 100)).setDirectoryListingEnabled(true), new HttpHandler() {
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
exchange.getResponseHeaders().add(Headers.LOCATION, "https://" + exchange.getHostName() + ":" + (exchange.getHostPort() + 363) + exchange.getRelativePath());
exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
}
}), "x-undertow-transport", ExchangeAttributes.transportProtocol())), new InMemorySessionManager("test"), new SessionCookieConfig())).build();
server.start();
SSLContext clientSslContext = createSSLContext(loadKeyStore("client.keystore"), loadKeyStore("client.truststore"));
LoadBalancingProxyClient proxy = new LoadBalancingProxyClient().addHost(new URI("https://localhost:8443"), null, new UndertowXnioSsl(Xnio.getInstance(), OptionMap.EMPTY, clientSslContext), OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).setConnectionsPerThread(20);
Undertow reverseProxy = Undertow.builder().setServerOption(UndertowOptions.ENABLE_HTTP2, true).addHttpListener(8081, bindAddress).addHttpsListener(8444, bindAddress, sslContext).setHandler(new ProxyHandler(proxy, 30000, ResponseCodeHandler.HANDLE_404)).build();
reverseProxy.start();
}
use of io.undertow.server.HttpHandler in project undertow by undertow-io.
the class BasicAuthServer method main.
public static void main(final String[] args) {
System.out.println("You can login with the following credentials:");
System.out.println("User: userOne Password: passwordOne");
System.out.println("User: userTwo Password: passwordTwo");
final Map<String, char[]> users = new HashMap<>(2);
users.put("userOne", "passwordOne".toCharArray());
users.put("userTwo", "passwordTwo".toCharArray());
final IdentityManager identityManager = new MapIdentityManager(users);
Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(addSecurity(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final SecurityContext context = exchange.getSecurityContext();
exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), IoCallback.END_EXCHANGE);
}
}, identityManager)).build();
server.start();
}
Aggregations