Search code examples
spring-data-restspring-hateoas

Id Encryption in spring-hateoas or Spring Rest Data


I have a question about a standard pattern or mechanism in spring-hateoas or Spring Rest Data about encrypting the IDs of the Resources/Entities.

The reason I am asking, a requirement to our project is that we don't deliver the id's of our objects to the outside world and they should not be used in GET Requests as Parameters.

I know, Spring Rest Data and spring-hateoas does not give the ids of the objects unless they are configured so but even that case I can see the ids in links.

I know I can use PropertyEditors or Converters to encrypt/decrypt ids before and after Json serialisation/deseritalisation but I just like to know is there a more standard way?

Thx for answers...


Solution

  • If you have the unique 'business id' property of your resource you can configure SDR to use it instead of the entity ID.

    First you have to create lookup method of your entity with this unique property:

    public interface MyEntityRepo extends JpaRepository<MyEntity, Long> {
    
      @RestResource(exported = false)
      Optional<CatalogResource> findByMyUniqueProperty(String myUniqueProperty);
    }
    

    Then use it to configure SDR:

    @Component
    public class DataRestConfig extends RepositoryRestConfigurerAdapter {
    
      @Override
      public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
    
        config.withCustomEntityLookup()
            .forRepository(MyEntityRepo.class, MyEntity::getMyUniqueProperty, MyEntityRepo::findByMyUniqueProperty);
    
        super.configureRepositoryRestConfiguration(config);
      }
    }
    

    After this customization you will have resource URI like this:

    http://localhost:8080/myEntities/myUniquePropertyValue1