Spring Security: global method security not working - spring

I have configured Keycloack and my auth server is working fine but since Spring deprecated previous OAuth2 support I am not sure my configuration is acurate. Its a simple learning application and I am trying to add Pre-authorization on method level so that the current authenticated user can add their workout data and view them for themselves. It also restricts delete endpoints only to admin user (fitnessadmin) But I am confused on configuration.
MY Controller class
#RestController
#RequestMapping("/workout")
public class WorkoutController {
#Autowired
private WorkoutService workoutService;
#PostMapping("/")
public void add(#RequestBody Workout workout) {
workoutService.saveWorkout(workout);
}
#GetMapping("/")
public List<Workout> findAll() {
return workoutService.findWorkouts();
}
#DeleteMapping("/{id}")
public void delete(#PathVariable Integer id) {
workoutService.deleteWorkout(id);
}
}
the repository class
public interface WorkoutRepository extends JpaRepository<Workout, Integer> {
#Query("SELECT w FROM Workout w WHERE w.user = ?#{authentication.name}")
List<Workout> findAllByUser();
}
service class
#Service
public class WorkoutService {
#Autowired
private WorkoutRepository repository;
#PreAuthorize("#workout.user == authentication.name")
public void saveWorkout(Workout workout) {
repository.save(workout);
}
public List<Workout> findWorkouts() {
return repository.findAllByUser();
}
public void deleteWorkout(Integer id) {
repository.deleteById(id);
}
}
configuration class
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authz -> authz
.mvcMatchers(HttpMethod.DELETE, "/**").hasAuthority("fitnessadmin")
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt());
}
#Bean
public SecurityEvaluationContextExtension
securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
}
application.yaml
server:
port: 8086
spring:
datasource:
url: jdbc:mysql://localhost:3306/db2?useSSL=false
username: username
password: password
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:8080/auth/realms/master
claim:
aud: fitnessapp
I have 3 users as mary, bill, rachel and only mary is "fitnessadmin" and would be able to delete.Rest of the users are "fitnessuser"
Here is the decoded token:
{
"exp" : 1635741988,
"nbf" : null,
"iat" : 1635734788,
"auth_time" : null,
"jti" : "9b319b1b-7687-4842-b211-02e3d1aaec3c",
"iss" : "http://localhost:8080/auth/realms/master",
"aud" : "fitnessapp",
"sub" : "8fe23dba-d692-4933-9bca-c5f69ff3d408",
"typ" : "Bearer",
"azp" : "fitnessapp",
"nonce" : null,
"session_state" : "c471f77f-8efa-449b-982d-90ea942f329e",
"at_hash" : null,
"c_hash" : null,
"name" : null,
"given_name" : null,
"family_name" : null,
"middle_name" : null,
"nickname" : null,
"preferred_username" : null,
"profile" : null,
"picture" : null,
"website" : null,
"email" : null,
"email_verified" : null,
"gender" : null,
"birthdate" : null,
"zoneinfo" : null,
"locale" : null,
"phone_number" : null,
"phone_number_verified" : null,
"address" : null,
"updated_at" : null,
"claims_locales" : null,
"acr" : "1",
"s_hash" : null,
"trusted-certs" : null,
"allowed-origins" : null,
"realm_access" : null,
"resource_access" : null,
"authorization" : null,
"cnf" : null,
"scope" : "fitnessapp",
"sid" : "c471f77f-8efa-449b-982d-90ea942f329e",
"user_name" : "bill",
"authorities" : [ "fitnessuser" ]
}
As I mentioned my confusion is with configuration class. This implementation gives below errors on different endpoints:
findAll():
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'authentication' cannot be found on object of type 'java.lang.Object[]' - maybe not public or not valid?
add():
403 Forbidden
A help would be greatly appreciated. Thanks in advance!
Update
I think I was missing SecurityEvaluationContextExtension as suggested in the comment and I have updated the code, but still I am getting the same error.

I guess the error you need to fix is authentication object in query.
public interface WorkoutRepository extends JpaRepository<Workout, Integer> {
#Query("SELECT w FROM Workout w WHERE w.user = ?#{authentication.name}")
List<Workout> findAllByUser();
}
Authentication is not an object you can access with this way but if you want to access spring bean you can create Authentication.java and create name field in that class.
Best way will be
public interface WorkoutRepository extends JpaRepository<Workout, Integer> {
#Query("SELECT w FROM Workout w WHERE w.user =:name")
List<Workout> findAllByUser(#Param("name") String name);
}

Related

Custom fields in logger with SpringBoot and JsonLayout

once I override the addCustomDataToJsonMap() method of JsonLayout how can I use that to set custom flields
I have added below code
#Setter
public class CustomLoggingConfig extends JsonLayout {
public static final String ADDITIONAL_INFO = "additionalInfo";
private String additionalInfo;
#Override
public void addCustomDataToJsonMap(Map<String, Object> var1, ILoggingEvent var2) {
var1.put(ADDITIONAL_INFO, additionalInfo);
}
}
and my logs are displayed like this:
{
"timestamp" : "2022-08-08 16:48:29.491",
"level" : "ERROR",
"thread" : "main",
"logger" : "jsonLogger",
"message" : "Exception occurred with message: Error in connecting to database",
"context" : "default",
"additionalInfo" : null
}
Question is how can I set additionalInfo?

ElasticsearchRepository skip null values

I have the Repo to interact with ES index:
#Repository
public interface RegDocumentRepo extends ElasticsearchRepository<RegDocument, String> {
}
RegDocument class is a POJO of reg-document index:
#Document(indexName = "reg-document")
#Data
#AllArgsConstructor
#NoArgsConstructor
public class RegDocument {
#Id
String id;
#Field(type = FieldType.Nested, includeInParent = true)
private List<Map<String, Object>> attachments;
private String author;
#Field(type = FieldType.Nested, includeInParent = true)
private List<Map<String, Object>> classification;
private String content;
private String intent;
#Field(type = FieldType.Nested, includeInParent = true)
private List<Map<String, Object>> links;
private String name;
#Field(name = "publication_date")
private String publicationDate;
private Integer raiting;
private Long status;
private String title;
private String type;
private String version;
}
To hide my business-logic I use service:
#RequiredArgsConstructor
#Service
public class SearchServiceImpl {
#Autowired
RegDocumentRepo regDocumentRepo;
public RegDocument updateRating(String uuid, Integer rating) throws IOException {
final RegDocument regDocument = regDocumentRepo
.findById(uuid)
.orElseThrow(() -> new IOException(String.format("No document with %s id", uuid)));
Integer ratingFromDB = regDocument.getRaiting();
ratingFromDB = ratingFromDB == null ? rating : ratingFromDB + rating;
regDocument.setRaiting(ratingFromDB);
final RegDocument save = regDocumentRepo.save(regDocument);
return save;
}
}
So I had the such document in my ES index:
{
"_index" : "reg-document",
"_type" : "_doc",
"_id" : "9wEgQnQBKzq7IqBZMDaO",
"_score" : 1.0,
"_source" : {
"raiting" : null,
"attachments" : null,
"author" : null,
"type" : "answer",
"classification" : [
{
"code" : null,
"level" : null,
"name" : null,
"description" : null,
"id_parent" : null,
"topic_type" : null,
"uuid" : null
}
],
"intent" : null,
"version" : null,
"content" : "В 2019 году размер материнского капитала составляет 453026 рублей",
"name" : "Каков размер МСК в 2019 году?",
"publication_date" : "2020-08-26 06:49:10",
"rowkey" : null,
"links" : null,
"status" : 1
}
}
But after I update my ranking score, I have next structure:
{
"_index" : "reg-document",
"_type" : "_doc",
"_id" : "9wEgQnQBKzq7IqBZMDaO",
"_score" : 1.0,
"_source" : {
"raiting" : 4,
"type" : "answer",
"classification" : [
{
"code" : null,
"level" : null,
"name" : null,
"description" : null,
"id_parent" : null,
"topic_type" : null,
"uuid" : null
}
],
"content" : "В 2019 году размер материнского капитала составляет 453026 рублей",
"name" : "Каков размер МСК в 2019 году?",
"publication_date" : "2020-08-26 06:49:10",
"status" : 1
}
}
As you can see, Java service skip NULL values. But if the field is nested, null values were saved.
ElasticSearch version - 7.8.0
maven dependency for spring-data:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
So how can i SAVE null values, not skip them?
**
UDP
**
I have investigated spring-data-elasticsearch-4.0.0 dependency and find out, as Best Answer author said, that MappingElasticsearchConverter.java has following methods:
#Override
public void write(Object source, Document sink) {
Assert.notNull(source, "source to map must not be null");
if (source instanceof Map) {
// noinspection unchecked
sink.putAll((Map<String, Object>) source);
return;
}
Class<?> entityType = ClassUtils.getUserClass(source.getClass());
TypeInformation<?> type = ClassTypeInformation.from(entityType);
if (requiresTypeHint(type, source.getClass(), null)) {
typeMapper.writeType(source.getClass(), sink);
}
Optional<Class<?>> customTarget = conversions.getCustomWriteTarget(entityType, Map.class);
if (customTarget.isPresent()) {
sink.putAll(conversionService.convert(source, Map.class));
return;
}
ElasticsearchPersistentEntity<?> entity = type.getType().equals(entityType)
? mappingContext.getRequiredPersistentEntity(type)
: mappingContext.getRequiredPersistentEntity(entityType);
writeEntity(entity, source, sink, null);
}
This methods explain why nested data was saved as null and wasn't skip. It just put Map inside.
So the next method use reflection in such way. So if it is a null value, it's just skip it:
protected void writeProperties(ElasticsearchPersistentEntity<?> entity, PersistentPropertyAccessor<?> accessor,
MapValueAccessor sink) {
for (ElasticsearchPersistentProperty property : entity) {
if (!property.isWritable()) {
continue;
}
Object value = accessor.getProperty(property);
if (value == null) {
continue;
}
if (property.hasPropertyConverter()) {
ElasticsearchPersistentPropertyConverter propertyConverter = property.getPropertyConverter();
value = propertyConverter.write(value);
}
if (!isSimpleType(value)) {
writeProperty(property, value, sink);
} else {
Object writeSimpleValue = getWriteSimpleValue(value);
if (writeSimpleValue != null) {
sink.set(property, writeSimpleValue);
}
}
}
}
There is no official solution. So i have created a Jira ticket
The null values of the inner objects are stored, because this happens when the Map with null values for keys is stored.
Entity properties with a null value are not persisted by Spring Data Elasticsearch are not persisted as this it would store information that is not needed for saving/retrieving the data.
If you need the null values to be written, this would mean, that we'd need to add some flag to the #Field annotation for this, can you add an issue in Jira (https://jira.spring.io/projects/DATAES/issues) for this?
Edit: Implemented in versions 4.0.4.RELEASE and 4.1.0.RC1

Preserving hostname on HATEOAS Resource with OpenFeign

I'm trying to add a URI to a resource located in a different microservice using OpenFeign and a ResourceAssembler, while preserving the hostname from the original request.
When making a REST request to a HATEOAS resource in another microservice, the resource.getId() method returns a link where the hostname is the Docker container hash instead of the original hostname used to make the request.
Controller
#RestController
#RequestMapping("/bulletins")
public class BulletinController {
// Autowired dependencies
#GetMapping(produces = MediaTypes.HAL_JSON_VALUE)
public ResponseEntity<PagedResources<BulletinResource>> getBulletins(Pageable pageable) {
Page<Bulletin> bulletins = bulletinRepository.findAll(pageable);
return ResponseEntity.ok(pagedResourceAssembler.toResource(bulletins, bulletinResourceAssembler));
}
}
Assembler
#Component
public class BulletinResourceAssembler extends ResourceAssemblerSupport<Bulletin, BulletinResource> {
private final AdministrationService administrationService;
#Autowired
public BulletinResourceAssembler(AdministrationService administrationService) {
super(BulletinController.class, BulletinResource.class);
this.administrationService = administrationService;
}
#Override
public BulletinResource toResource(Bulletin entity) {
Resource<Site> siteRessource = administrationService.getSiteBySiteCode(entity.getSiteCode());
\\ Set other fields ...
bulletinRessource.add(siteRessource.getId().withRel("site"));
return bulletinRessource;
}
}
Feign Client
#FeignClient(name = "${feign.administration.serviceId}", path = "/api")
public interface AdministrationService {
#GetMapping(value = "/sites/{siteCode}")
Resource<Site> getSiteBySiteCode(#PathVariable("siteCode") String siteCode);
}
Bulletin Resource
#Data
public class BulletinResource extends ResourceSupport {
// fields
}
Expected result
curl http://myhost/api/bulletins
{
"_embedded" : {
"bulletinResources" : [ {
"entityId" : 1,
"_links" : {
"self" : {
"href" : "http://myhost/api/bulletins/1"
},
"site" : {
"href" : "http://myhost/api/sites/000"
}
}
} ]
},
[...]
}
Actual result
curl http://myhost/api/bulletins
{
"_embedded" : {
"bulletinResources" : [ {
"entityId" : 1,
"_links" : {
"self" : {
"href" : "http://myhost/api/bulletins/1"
},
"site" : {
"href" : "http://b4dc1a02586c:8080/api/sites/000"
}
}
} ]
},
[...]
}
Notice the site href is b4dc1a02586c, which is the Docker container id.
The solution was to manually define a RequestInterceptor for the FeignClient and manually add the X-Forwarded-Host header, as well as define a ForwardedHeaderFilter bean in the service the request was made to.
Client Side
public class ForwardHostRequestInterceptor implements RequestInterceptor {
private static final String HOST_HEADER = "Host";
private static final String X_FORWARDED_HOST = "X-Forwarded-Host";
#Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
if (requestAttributes == null) {
return;
}
HttpServletRequest request = requestAttributes.getRequest();
String host = request.getHeader(X_FORWARDED_HOST);
if (host == null) {
host = request.getHeader(HOST_HEADER);
}
requestTemplate.header(X_FORWARDED_HOST, host);
}
}
Producer side
The producer side also required modification as per the discussion on
https://github.com/spring-projects/spring-hateoas/issues/862
which refers to the following documentation
https://docs.spring.io/spring-hateoas/docs/current-SNAPSHOT/reference/html/#server.link-builder.forwarded-headers
which states to add the following bean in order to use forward headers.
#Bean
ForwardedHeaderFilter forwardedHeaderFilter() {
return new ForwardedHeaderFilter();
}

Getting duplicate items when querying a collection with Spring Data Rest

I'm having duplicate results on a collection with this simple model: an entity Module and an entity Page. A Module has a set of pages, and a Page belongs to the module.
This is set up with Spring Boot with Spring Data JPA and Spring Data Rest.
The full code is accessible on GitHub
Entities
Here's the code for the entities. Most setters removed for brevity:
Module.java
#Entity
#Table(name = "dt_module")
public class Module {
private Long id;
private String label;
private String displayName;
private Set<Page> pages;
#Id
public Long getId() {
return id;
}
public String getLabel() {
return label;
}
public String getDisplayName() {
return displayName;
}
#OneToMany(mappedBy = "module")
public Set<Page> getPages() {
return pages;
}
public void addPage(Page page) {
if (pages == null) {
pages = new HashSet<>();
}
pages.add(page);
if (page.getModule() != this) {
page.setModule(this);
}
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Module module = (Module) o;
return Objects.equals(label, module.label) && Objects.equals(displayName, module.displayName);
}
#Override
public int hashCode() {
return Objects.hash(label, displayName);
}
}
Page.java
#Entity
#Table(name = "dt_page")
public class Page {
private Long id;
private String name;
private String action;
private String description;
private Module module;
#Id
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getAction() {
return action;
}
public String getDescription() {
return description;
}
#ManyToOne
public Module getModule() {
return module;
}
public void setModule(Module module) {
this.module = module;
this.module.addPage(this);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Page page = (Page) o;
return Objects.equals(name, page.name) &&
Objects.equals(action, page.action) &&
Objects.equals(description, page.description) &&
Objects.equals(module, page.module);
}
#Override
public int hashCode() {
return Objects.hash(name, action, description, module);
}
}
Repositories
Now the code for the Spring repositories, which is fairly simple:
ModuleRepository.java
#RepositoryRestResource(collectionResourceRel = "module", path = "module")
public interface ModuleRepository extends PagingAndSortingRepository<Module, Long> {
}
PageRepository.java
#RepositoryRestResource(collectionResourceRel = "page", path = "page")
public interface PageRepository extends PagingAndSortingRepository<Page, Long> {
}
Config
The configuration comes from 2 files:
Application.java
#EnableJpaRepositories
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
application.properties
spring.jpa.database = H2
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto=validate
spring.datasource.initialize=true
spring.datasource.url=jdbc:h2:mem:demo;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.data.rest.basePath=/api
Database
Finally the db schema and some test data:
schema.sql
drop table if exists dt_page;
drop table if exists dt_module;
create table DT_MODULE (
id IDENTITY primary key,
label varchar(30) not NULL,
display_name varchar(40) not NULL
);
create table DT_PAGE (
id IDENTITY primary key,
name varchar(50) not null,
action varchar(50) not null,
description varchar(255),
module_id bigint not null REFERENCES dt_module(id)
);
data.sql
INSERT INTO DT_MODULE (label, display_name) VALUES ('mod1', 'Module 1'), ('mod2', 'Module 2'), ('mod3', 'Module 3');
INSERT INTO DT_PAGE (name, action, description, module_id) VALUES ('page1', 'action1', 'desc1', 1);
That's about it. Now, I run thus from the command line to start the application: mvn spring-boot:run. After the application starts, I can query it's main endpoint like this:
Get API
$ curl http://localhost:8080/api
Response
{
"_links" : {
"page" : {
"href" : "http://localhost:8080/api/page{?page,size,sort}",
"templated" : true
},
"module" : {
"href" : "http://localhost:8080/api/module{?page,size,sort}",
"templated" : true
},
"profile" : {
"href" : "http://localhost:8080/api/alps"
}
}
}
Get all modules
curl http://localhost:8080/api/module
Response
{
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/module"
}
},
"_embedded" : {
"module" : [ {
"label" : "mod1",
"displayName" : "Module 1",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/module/1"
},
"pages" : {
"href" : "http://localhost:8080/api/module/1/pages"
}
}
}, {
"label" : "mod2",
"displayName" : "Module 2",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/module/2"
},
"pages" : {
"href" : "http://localhost:8080/api/module/2/pages"
}
}
}, {
"label" : "mod3",
"displayName" : "Module 3",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/module/3"
},
"pages" : {
"href" : "http://localhost:8080/api/module/3/pages"
}
}
} ]
},
"page" : {
"size" : 20,
"totalElements" : 3,
"totalPages" : 1,
"number" : 0
}
}
Get all pages for one module
curl http://localhost:8080/api/module/1/pages
Response
{
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/module/1/pages"
}
},
"_embedded" : {
"page" : [ {
"name" : "page1",
"action" : "action1",
"description" : "desc1",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/page/1"
},
"module" : {
"href" : "http://localhost:8080/api/page/1/module"
}
}
}, {
"name" : "page1",
"action" : "action1",
"description" : "desc1",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/page/1"
},
"module" : {
"href" : "http://localhost:8080/api/page/1/module"
}
}
} ]
}
}
So as you can see, I'm getting the same page twice here. What's going on?
Bonus question: Why this works?
I was cleaning the code to submit this question, and in order to make it more compact, I moved the JPA Annotations on the Page entity to field level, like this:
Page.java
#Entity
#Table(name = "dt_page")
public class Page {
#Id
private Long id;
private String name;
private String action;
private String description;
#ManyToOne
private Module module;
...
All the rest of the class remains the same. This can be seen on the same github repo on branch field-level.
As it turns out, executing the same request with that change to the API will render the expected result (after starting the server the same way I did before):
Get all pages for one module
curl http://localhost:8080/api/module/1/pages
Response
{
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/module/1/pages"
}
},
"_embedded" : {
"page" : [ {
"name" : "page1",
"action" : "action1",
"description" : "desc1",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/page/1"
},
"module" : {
"href" : "http://localhost:8080/api/page/1/module"
}
}
} ]
}
}
This is causing your issue (Page Entity):
public void setModule(Module module) {
this.module = module;
this.module.addPage(this); //this line right here
}
Hibernate uses your setters to initialize the entity because you put the JPA annotations on getters.
Initialization sequence that causes the issue:
Module object created
Set Module properties (pages set is initialized)
Page object created
Add the created Page to Module.pages
Set Page properties
setModule is called on the Page object and this adds (addPage) the current Page to Module.pages the second time
You can put the JPA annotations on the fields and it will work, because setters won't be called during initialization (bonus question).
I had this issue and I just changed fetch=FetchType.EAGER to fetch=FetchType.LAZY
This solved my problem!

Custom response for root request int the Spring REST HATEOAS with both RepositoryRestResource-s and regular controllers

Let's say I have two repositories:
#RepositoryRestResource(collectionResourceRel = "person", path = "person")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findByLastName(#Param("name") String name);
}
and
#RepositoryRestResource(collectionResourceRel = "person1", path = "person1")
public interface PersonRepository1 extends PagingAndSortingRepository<Person1, Long> {
List<Person1> findByLastName(#Param("name") String name);
}
with one regular controller:
#Controller
public class HelloController {
#RequestMapping("/hello")
#ResponseBody
public HttpEntity<Hello> hello(#RequestParam(value = "name", required = false, defaultValue = "World") String name) {
Hello hello = new Hello(String.format("Hello, %s!", name));
hello.add(linkTo(methodOn(HelloController.class).hello(name)).withSelfRel());
return new ResponseEntity<>(hello, HttpStatus.OK);
}
}
Now, a response for http://localhost:8080/ is:
{
"_links" : {
"person" : {
"href" : "http://localhost:8080/person{?page,size,sort}",
"templated" : true
},
"person1" : {
"href" : "http://localhost:8080/person1{?page,size,sort}",
"templated" : true
}
}
}
but I want to get something like this:
{
"_links" : {
"person" : {
"href" : "http://localhost:8080/person{?page,size,sort}",
"templated" : true
},
"person1" : {
"href" : "http://localhost:8080/person1{?page,size,sort}",
"templated" : true
},
"hello" : {
"href" : "http://localhost:8080/hello?name=World"
}
}
}
#Component
public class HelloResourceProcessor implements ResourceProcessor<RepositoryLinksResource> {
#Override
public RepositoryLinksResource process(RepositoryLinksResource resource) {
resource.add(ControllerLinkBuilder.linkTo(HelloController.class).withRel("hello"));
return resource;
}
}
based on
http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.customizing-json-output
How to add links to root resource in Spring Data REST?
You need to have a ResourceProcessory for your Person resource registered as a Bean. see https://stackoverflow.com/a/24660635/442773

Resources