3
votes

I am trying to return a response body in my "successfullAuthentication" method in "UsernamePasswordAuthenticationFilter" using HATEOAS, but is returning the links in this format:

"links": [
    {
        "rel": "self",
        "href": "http://localhost:8080/api/users/5c55ee26911e9f04acb77c91",
        "hreflang": null,
        "media": null,
        "title": null,
        "type": null,
        "deprecation": null
    },

I would like it to return HAL json format so it would look like this:

"_links": {
    "self": {
        "href": "http://localhost:8080/api/users/5c55ee26911e9f04acb77c91"
    },

I have this in my method (response is HttpServletResponse):

User user = userService.findById(authResult.getName());
String json = Jackson.toJsonString(userResourceAssembler.toResource(user));
response.setContentType("application/hal+json");
response.setCharacterEncoding("UTF-8");
response.addHeader(jwtConfig.getHeader(), jwtConfig.getPrefix() + token);
response.getWriter().write(json);

I also have this in my WebConfig: @EnableHypermediaSupport(type = { EnableHypermediaSupport.HypermediaType.HAL })

Does anyone know why this is happening?

2

2 Answers

1
votes

I found the answer in this github issue: https://github.com/spring-projects/spring-hateoas/issues/270#issuecomment-145606558

Basically:

private String convertToHalString(ResourceSupport resource) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new Jackson2HalModule());
    mapper.setHandlerInstantiator(new Jackson2HalModule.HalHandlerInstantiator(
            new EvoInflectorRelProvider(), null, null));
    String resourceString = null;
    try {
        resourceString = mapper.writeValueAsString(resource);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return resourceString;
}
0
votes

Try to extend all model classes- to add HATEOAS links –

with org.springframework.hateoas.ResourceSupport class

Presuming you have respective URI's in controller class

Link link = ControllerLinkBuilder
           .linkTo(UserController.class)
           .slash(user.getXXX())
           .withSelfRel();

//for single resource
user.add(link);

Link userLink = ControllerLinkBuilder
            .linkTo(ControllerLinkBuilder
            .methodOn(UserController.class).getAllUsers())
            .withSelfRel();

//For collections
userList.add(userLink);

Reference: https://spring.io/understanding/HATEOAS