Redirect HTTP to HTTPS in Undertow - https

How can one configure HTTP->HTTPS redirection in Undertow? I've looked through Undertow's codebase, there are some classes that seem to be relevant (e.g. RedirectHandler). Also, Undertow documentation (Predicates Attributes and Handlers) seems to target exactly this problem among others. But I'm not sure where to start.
Basically, what I'm looking for is some counterpart to Apache's mod_rewrite configuration:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
Thanks!

This answer pointed in the right direction. Programmatically, one has to add a SecurityConstraint to Builder and set ConfidentialPortManager:
DeploymentInfo servletBuilder = Servlets.deployment();
servletBuilder.addSecurityConstraint(new SecurityConstraint()
.addWebResourceCollection(new WebResourceCollection()
.addUrlPattern("/*"))
.setTransportGuaranteeType(TransportGuaranteeType.CONFIDENTIAL)
.setEmptyRoleSemantic(EmptyRoleSemantic.PERMIT))
.setConfidentialPortManager(new ConfidentialPortManager() {
#Override
public int getConfidentialPort(HttpServerExchange exchange) {
return 443;
}
}
);

Related

ratpack: implementing a custom PublicAddress to force https

I was on a pac4j mail thread discussing why the redirect url ratpack-pac4j uses is using http even when the original page request is served over https. I did some digging and it looks like ratpack-pac4j is using the InferringPublicAddress. This works for local development, but because my elasticbean host proxies 443 to 80, ratpack-pac4j thinks it's over http and uses http for the redirect url. I want this call to be over https when on the server.
I'm trying to register a custom PublicAddress class that always returns http in development mode, but https in production mode:
.registry(Guice.registry(b -> {
b
.module(SessionModule.class)
.module(ThymeleafModule.class, conf -> conf.templatesMode("LEGACYHTML5"))
.add(PublicAddress.class, ForcedHttpsPublicAddress.create()); //PublicAddress.class, PublicAddress.inferred("https"));
}))
...
static private class ForcedHttpsPublicAddress implements PublicAddress
{
static ForcedHttpsPublicAddress create() {
return new ForcedHttpsPublicAddress();
}
ForcedHttpsPublicAddress() {
}
}
But when I call ctx.get(PublicAddress.class), it's still returning InferringPublicAddress. Am I registering the custom PublicAddress incorrectly?
Got help on the Ratpack forum. I needed to bind it instead of add it.
.bind(PublicAddress.class, ForcedHttpsPublicAddress.class)

Spring MVC Url Why do I get a 404 when I encode a linefeed in the url

I am sending an url with certain parameters to my controller, which works generally fine. I am using javascript function encodeURI() to encode the parameter.
But as soon, as there is a linefeed, I receive a 404 error.
This is a working url:
http://localhost:8080/Weasy/virtualtable/execQuery/46/select%20*%20from%20payment
This is a non-working url:
http://localhost:8080/Weasy/virtualtable/execQuery/46/select%20*%20%0Afrom%20payment
And this is my controller method:
#RequestMapping("execQuery/{schema_id}/{query}")
public ModelAndView execQuery(
#PathVariable("schema_id") Integer schemaId
, #PathVariable("query") String query) throws Exception {
SrcSchema schema = this.srcschemaService.getRowById(schemaId);
ModelAndView mav = new ModelAndView("virtualtable/form");
mav.addObject("schema", schema);
mav.addObject("query", query);
try {
int limit = 10;
List<Map<String, Object>> rows = jdbcService.executeQuery(schema.getConnection(), query, limit);
mav.addObject("rows", rows);
mav.addObject("message", "<span class='msg-info'>Result Set reduced to "+limit+" rows</span>");
} catch (Exception ex) {
logger.error("Error executing sql", ex);
mav.addObject("message", "<span class='msg-error'>"+ex.getMessage()+"</span>");
}
return mav;
}
Why does it not work?
I do not think it is your app. I guess it is your web server blocking the request as you are using an odd character. Apache for example denies the access to urls containing %2F (/), %5F (\) or %00 (NULL). As a rule, the ASCII characters between %00 and %1F, named control characters, should not be present at urls, and %0A is one of them.
My advice is you should parse your query and get rid of, not only %0A but also any problematic character, before doing the request.
If you still want to make it works I think you need to include a rewriterule in your .htaccess (I guess you are using Apache), and use a regular expression to remove the line feed and redirect to the same url without that character.
Apache URL Rewriting Guide

appharbor force HTTPS for static files

I have a requirement to ensure all traffic on my website is redirected to HTTPS if it is requested over HTTP. When we deploy the site to appharbor, we use the custom RequireHttpsAttribute which works well for our MVC controllers.
However we also want to force any request for static files (images, stylesheets, javascript) via HTTP to be sent to HTTPS. Trying it using the web.config rewrite rules ends up in a redirect loop due to the load balancer sending https request to the web server as http.
Does anyone have any ideas on how to achieve this?
After receiving a reply from appharbor support, one of their suggestions was to implement code similar to the custom RequireHttpsAttribute for static files as well.
So I created a class called HttpRequestModule, and set it up to run for all requests (runAllManagedModulesForAllRequests set to true) I was able to force any direct requests to HTTP urls to redirect to HTTPS.
class HttpRequestModule : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(CheckHttpRequest);
}
private void CheckHttpRequest(object sender, EventArgs a)
{
if (app.Context.Request.IsSecureConnection) return;
if (app.Contact.Request.IsLocal) return;
if (string.Equals(app.Context.Request.Headers["X-Forwarded-Proto"],
"https",
StringComparison.InvariantCultureIgnoreCase))
{
return;
}
var secureUrl = "https://" + app.Context.Request["HTTP_HOST"] + HttpContext.Current.Request.RawUrl;
app.Context.Response.Redirect(secureUrl);
}
}

Redirect permanently 301 in blogengine.net (global.asax)

i want to redirect my old address www.informarea.it/BlogEngine to new address www.informarea.it...
*my global.asax of blogengine.net is *
void Application_BeginRequest(object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
// Attempt to perform first request initialization
FirstRequestInitialization.Initialize(context);
}
*can i make to apply the code of redirect permanently? *
if (app.url.ToString().ToLower().Contains("http://www.informarea.it/BlogEngine"))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location",url.Replace("http://www.informarea.it/blogengine", "http://www.informarea.it"));
}
Can Someone help me?
thank you very much
Fabry
This should redirect any query where the path starts with /BlogEngine to the same url with the /BlogEngine removed.
if(Request.Url.PathAndQuery.StartsWith("/BlogEngine", StringComparison.OrdinalIgnoreCase)) {
Response.RedirectPermanent(Request.Url.PathAndQuery.Substring(11), true);
}
Pros:
Gives a 301 Redirect like you requested
Keeps the rest of the path and query string intact for the following request
Cons:
Requires .net 4.0 (Version 2.7 of BlogEngine is targeted at 4.0 so I don't think this will be an issue.)

CodeIgniter, rewrite urls, call custom controller

I have completed CMS.
This CMS have many controllers: news, content, articles, etc.
Also have modules like "modules/shop/controllers/cart.php", "modules/shop/controllers/items.php".
ATM URLs are:
/shop/some-category/
/shop/nokia/n73.html
/content/about-company.html
/articles/phones/full/1.html
Now I need urls like:
- /nokia.html
- /my/super/article-about-phones.html
So, I need custom URLs for any controlles (shop, news, content, etc).
As I know, I can't execute controller from controller.
How I can solve a problem?
I have no idea how to rewrite Router core class. Any ideas?
For me I have 1 way - rewrite architecture of full product but I have no time :(
Thnx alot.
P.S. ATR routes.php is:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$lang_prefix = '(([a-z]{2}/)?)';
$route[$lang_prefix.'ajax/shop/(.*)'] = "shop/ajax/$3";
$route['cron/(.*)'] = "cron/$1";
$route[$lang_prefix.'content/(.*)'] = "content/index";
$route[$lang_prefix.'faq/ask/(.*)'] = "faq/ask";
$route[$lang_prefix.'faq/(.*)'] = "faq/index";
$route[$lang_prefix.'sitemap'] = "sitemap/index";
$route[$lang_prefix.'contact'] = "contacts/index";
$route[$lang_prefix.'news/(.*?)/full/[0-9]+'] = "news/full";
$route[$lang_prefix.'news/(.*)'] = "news/index";
$route[$lang_prefix.'compare/[0-9]+[0-9\/]+'] = "shop/compare";
$route[$lang_prefix.'cart/(.*?)'] = "shop/cart/$3";
$route[$lang_prefix.'cart'] = "shop/cart";
$route[$lang_prefix.'order'] = "shop/order";
$route[$lang_prefix.'order/check'] = "shop/order";
$route[$lang_prefix.'order/successful/[A-z_\-0-9]+'] = "shop/order/successful";
$route[$lang_prefix.'search/(name|price|rating)/(asc|desc)(.*)'] = "shop/search";
$route[$lang_prefix.'shop/(.*)/(name|price|rating)/(asc|desc)(.*?)'] = "shop/items/index";
$route[$lang_prefix.'shop/(.*?)/(.*?)/add-comment'] = "shop/items/add_comment";
$route[$lang_prefix.'shop/(.*?)/(.*?)'] = "shop/items/details";
$route[$lang_prefix.'shop/(.*)'] = "shop/items/index";
$route[$lang_prefix.'feedback'] = "feedback/index";
$route[$lang_prefix.'callback'] = "feedback/index";
$route[$lang_prefix.'article/(.*?)/full/(.*)'] = "articles/full";
$route[$lang_prefix.'article/(.*)'] = "articles/index";
$route[$lang_prefix.'gallery/(.*?)/full/(.*)'] = "gallery/full";
$route[$lang_prefix.'gallery/(.*)'] = "gallery/index";
$route[$lang_prefix.'admin/ajax/(.*)'] = "admin/ajax/$3";
$route[$lang_prefix.'admin'] = "admin/main/index";
$route[$lang_prefix.'admin/login'] = "admin/auth/login";
$route[$lang_prefix.'admin/logout'] = "admin/auth/logout";
$route[$lang_prefix.'admin/(.*)'] = "admin/$3";
$route['default_controller'] = "shop/showcase";
You could use a mod_rewrite to direct all requests to a .html file to go to a special static content controller. So:
my/super/article-about-phones.html
would redirect to:
/content/static/article-about-phones/
This might look something like this:
Options +FollowSymLinks
RewriteBase /
RewriteEngine On
RewriteRule ^(.+)/([^/]+)\.html$ /content/static/$1/ [NC,L]

Resources