How to construct URI in Java Spring Boot

Last modified date

Comments: 0

Contents

Problem

Constructing a URI in Java might seem like a trivial task. Using something like String.format you could concatenate the different parts of a URI together.

String.format("https://{}/{}", myHost, myPath

However using raw strings is insecure and could leave your code vulnerable to injection attacks.

I was recently made aware of this vulnerability when running some pre-production code for a Micro Focus Fortify Scan.

Solution

The correct way to construct URI’s in Java is to use the UriComponentsBuilders object provided in the Spring Boot framework

It is a very simple, easy to understand and secure way to construct URI’s.

To construct a simply URI like this:

https://jaktech.co.uk/java

You can use UriComponentsBuilder like this:

UriComponentsBuilder.newInstance()
                .scheme("https")
                .host("jaktech.co.uk")
                .path("java")
                .build()
                .toUriString();

To construct a URI with query string params like this:

https://jaktech.co.uk/s=java

You can add those fields into the builder:

UriComponentsBuilder.newInstance()
                .scheme("https")
                .host("jaktech.co.uk")
                .path("java")
                .queryParam("s", "java")
                .build()
                .toUriString();

This is how you can securely construct URI’s in Java Spring Boot.

JakTech

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.