Search code examples
javaspringspring-bootspring-hateoashateoas

Context Path not considered in HATEOAS links when upgrading from Spring Boot 1.5.9 to 2.2.6


I have recently upgraded an older application, based on Spring Boot, from version 1.5.9 to 2.2.6.

Unfortunately, after upgrading, the urls generated with HATEOAS are changed. Basically the context-path is missing from the Links now.

Example:

Before: https://domain.test.com/service/api/endpoint
Now:    https://domain.test.com/service/endpoint

Right now I am using the following configs in application properties:

server.servlet.context-path: /api
server.forward-headers-strategy: FRAMEWORK
spring.data.rest.basePath: /api

(With none, the host is totally different(because of the x-forwarded-host. I have also tried with native, but same behavior)

I have also created a ForwardedHeaderFilter bean.

    @Bean
    public ForwardedHeaderFilter forwardedHeaderFilter() {
        return new ForwardedHeaderFilter();
    }

Is there anything I can do to bypass this issue? Am I doing something wrong ?

One alternative would be to adjust the api gateway, but this would be really complicated from a business process perspective so I would prefer a more technical approach.

Thank you !


Solution

  • As a temporary solution, until I have time to really take a deeper look, I have created a new Utility class, that takes care of adjusting the path:

    public class LinkUtil {
        private LinkUtil() {
        }
    
        @SneakyThrows
        public static <T> Link linkTo(T methodOn) {
            String rawPath = WebMvcLinkBuilder.linkTo(methodOn).toUri().getRawPath();
            rawPath = StringUtils.remove(rawPath, "/service");
            BasicLinkBuilder basicUri = BasicLinkBuilder.linkToCurrentMapping().slash("/api").slash(rawPath);
    
            return new Link(basicUri.toString());
        }
    }
    
    

    Where /api is the context-path.

    Then I use it like this:

    Link whateverLink = LinkUtil.linkTo(methodOn(WhateverClass.class).whateverMethod(null)).withRel("whatever-rel));