Přeskočit na hlavní obsah

Three ways to redirect HTTP requests to HTTPs in WildFly and JBoss EAP

WildFly application server (and JBoss EAP) supports several simple ways how to redirect the communication from plain HTTP to TLS protected HTTPs. This article presents 3 ways. Two are on the application level and the last one is on the server level valid for requests to all deployments.

1. Request confidentiality in the deployment descriptor

The first way is based on the Servlet specification. You need to specify which URLs should be protected in the web.xml deployment descriptor. It's the same approach as the one used for specifying which URLs require authentication/authorization. Just instead of requesting an assigned role, you request a transport-guarantee.

Sample content of the WEB-INF/web.xml


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
   version="3.1">
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>All confidential</web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <user-data-constraint>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>
    </security-constraint>
</web-app>

As we used the /* URL pattern, all the URLs will request switching from http to https.

2. Request the redirect from Undertow handler in your application

The second approach is similar to the first one. It also depends on the configuration file within the application. Instead of using a Java EE specification, it employs Undertow features. Undertow web server is one of the core components in the WildFly. This approach is lacking detailed description in the WildFly/EAP documentation, but the great starting point is Undertow documentation itself - section Predicates Attributes and Handlers.

What we want to do is to define a handler (a rule) which will all incoming requests having scheme==http redirect to the same URL but with the https scheme used.

So let's simply define the configuration file with the rule WEB-INF/undertow-handlers.conf:


equals(%{SCHEME},"http") -> redirect(https://%v:8443%U%q)

The left equals(...) part is a predicate and the right redirect(...) part is a handler. String templates starting with the percent sign % are called exchange attributes. They may have a long or a short form:

%{LOCAL_SERVER_NAME}  %v     Local server name
%{REQUEST_URL}        %U     Requested URL path
%{QUERY_STRING}       %q     Query string (prepended with a '?' if it exists,
                             otherwise an empty string)
%{SCHEME}                    Request scheme

Some attributes (e.g. %{SCHEME}) are missing in the documentation, you can find them in the code or in the JavaDoc.

As you can see, there is a small disadvantage of this solution. We have to know the https port mapping upfront.

3. Request redirect in the Undertow subsystem

Sometime you may want to have HTTPs used for all the applications. In such cases use the way of configuring the Undertow subsystem within the WildFly configuration. The method is the same as in point 2, just the place where the predicates and handlers (rules) is defined is a different one. The Undertow subsystem in WildFly provides a model for the build-in predicates and handlers. You may use the following JBoss CLI commands:


/subsystem=undertow/configuration=filter/rewrite=http-to-https:add( \
  redirect=true, \
  target="https://%{LOCAL_SERVER_NAME}:${jboss.https.port:8443}%{REQUEST_URL}%{QUERY_STRING}")

/subsystem=undertow/server=default-server/host=default-host/filter-ref=http-to-https:add( \
  predicate="equals(%{SCHEME},http)")

So we specified the new rewrite handler with redirect=true. Then we mapped this handler in a new filter-ref resource using it just for requests matching the given predicate.

And that's it. This time we simply resolved the "whats-the-port" issue by using the default https port expression in Wildfly - ${jboss.https.port:8443}.

Bonus - Nginx proxy

Sometime you may want to use another web server. Then you can proxy requests to the WildFly and solve HTTPs redirects completely out of WildFly. Sample config in the Nginx:


server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    return 301 https://$host$request_uri;
}
server {
    listen 443 ssl;
    server_name my-server.my-company.com;
    server_tokens off;
    location / {
            proxy_pass  http://127.0.0.1:8080/;
            ...
   }
   ...
}

Komentáře

Populární příspěvky z tohoto blogu

Simple TLS certificates in WildFly 18

It's just 2 weeks when WildFly 18 was released. It includes nice improvements in TLS certificates handling through ACME protocol (Automatic Certificate Management Environment), it greatly simplifies obtaining valid HTTPS certificates.

There was already a support for the Let's Encrypt CA in WildFly 14 as Farah Juma described in her blog post last year.

New WildFly version allows using other CA-s with ACME protocol support.
It also adds new switch --lets-encrypt to interactive mode of security enable-ssl-http-server JBoss CLI commands. Let's try it.

Before we jump on WildFly configuration, let's just mention the HTTPs can be used even in the default configuration and a self-signed certificate is generated on the fly. Nevertheless, it's not secure and you should not use it for any other purpose than testing.

Use Let's Encrypt signed certificate for HTTPs application interfaceStart WildFly on a machine with the public IP address. Run it on the default HTTP(80) and…

Zipujeme efektivně

Jedna ze základních vlastností Javy je práce se ZIP archívy, ať už jsou to knihovny tříd a spustitelné JARy, webové aplikace (war), nebo třeba JEE bumbrlíčci (ear). Není tedy divu, že i přímo v základním API je implementována práce s těmito archívy. Slouží k tomu třídy v balíku java.util.zip a nejzajímavější z nich jsou ZipOutputStream a ZipInputStream. Příkladem budiž vytvoření zipu: //Vytvorime Zip ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("javlog.zip")); //V Zipu chceme mit jeden textovy soubor zos.putNextEntry(new ZipEntry("priznani.txt")); //naplnime obsah textoveho souboru zos.write("Máme rádi Javu!".getBytes()); //zavrem entry (priznani.txt) zos.closeEntry(); //zavrem stream zos.close(); a jeho rozbalení: ZipInputStream zis = new ZipInputStream(new FileInputStream("javlog.zip")); ZipEntry zipEntry; //budem predpokladat, ze v ZIPu mame jen textove soubory a tak je vypisem do konzole while ((zipEntry = zis.getNextE…

jd-cli – Command line Java Decompiler

Kdo by neznal jd-gui Java Decompiler (z free.fr) a jeho sourozence, pluginy pro IDE – Eclipse a IntelliJ. Ale nechyběla vám také někdy možnost rychle decompilovat celý JAR nebo WAR do adresáře, případně zobrazit si decompilovanou třídu jen v konzoli bez nutnosti spouštění GUI?
Jestliže ano, pak se zkuste podívat na utilitku jd-cli, která toto všechno umožňuje. Tato aplikace je jednoduchý wrapper nad nativní knihovnou pro jd-gui InelliJ plugin.

Kde všude tato java aplikace běží?
WindowsLinuxMac OSX Kompilace Potřebujete git a Maven.
git clone git@github.com:kwart/jd-cmd.git cd jd-cmd mvn clean package
Rozbalte jd-cli-[version].zip (.tar.gz) někam, kam odkazuje systémová PATH proměnná (C:\Windows nebo $HOME/bin) - distribuce obsahuje i spouštěcí skripty (shell a batch), takže pak už jen vesele voláte
jd-cli [aParametry] Příklady použitíjd-cli HelloWorld.class Zobrazí dekompilovanou třídu v konzoli

jd-cli --skipResources -n -g ALL app.jar Dekompiluje obsah archivu app.jar do souboru app…