Disable setting up Audit fields in create/update requests in Spring Data REST

649 views Asked by At

I'm using combination of various Spring components - Boot (2.3), Data, Data REST, Springdoc. In my model objects I use auditing - I annotate some fields with @CreatedBy, @CreatedDate etc. I would like to disable possibility to set value of those audit fields through REST API. At the same time, I want this information to be available when retrieving data.

Seems like quite obvious thing to do, but I'm unable to find a way to do this. By default I can easily provide those values in API calls and see them persisted.

Ideally, such configuration change would be visible also in OpenAPI spec generated by Springdoc (in model of request).

2

There are 2 answers

1
kkonrad On BEST ANSWER

So it turns out that I'm silly :)

So my error was that authentication and authorization was disabled at that time. Once enabled, I wasn't able to provide values for createdBy and other fields as they were just getting overridden with correct values.

When it comes to OpenAPI specification, I had to annotate fields with:

@Schema(accessMode = Schema.AccessMode.READ_ONLY)

from io.swagger.v3.oas.annotations.media.Schema;. This resulted in correct info. See Swagger view:

enter image description here

1
yejianfengblue On

I guess the problem comes from your bad design. Please consider your design is correct or not. I guess in your design, besides Spring Data REST endpoints (APIs), there are other code which can create and update your object and save to database.

You question has nothing to do with Spring Data REST. Audit fields annotated with @Createdxx and @LastModifiedxx is auto updated by Spring Data repository, and Spring Data REST just calls the Spring Data repository to persist data.

Answer below two questions helps clarify your design.

Question 1: If you want to keep create (POST) endpoints which are created by Spring Data REST by default, and you don't want audit fields annotated with @Createdxx to be set, then what code is responsible to set those audit fields? Assume you send a POST request to create an object, do you want createdBy and createdDate to be null? Or would createdBy and createdDate be updated later by other code?

Question 2: If you want to keep update (PUT/PATCH) endpoints which are created by Spring Data REST by default, and you don't want audit fields annotated with @LastModifiedxx to be updated, then what code is responsible to update those audit fields? And this also results in imcomplete audit (you make update, but lastModified info not updated).