Mask SSN in spring data rest response body - spring

I am creating a rest service using Spring REST. In few services like Identification, I need to Mask SSN in response. (without usingJSON ignore or JsonProperty)
If clients send the SSN in the request body, the response body for SSN should be masked as shown below. (example, Postman requests body and response)
SSN should be masked as xxx-xxxx-1235 in the response body.
Is there any way in spring data rest to achieve this? Or any common solution that could be applied on all entities/controller when ResponseEntity is returned (like Interceptor)?

I believe the jackson #JsonGetter could be used for this case.
#JsonGetter("ssn")
public String getCensoredSsn() {
return Something.CensorSsn(ssn);
}

I was able to do this two ways. First was to override the get method for the required field and mask it right there. Other way was through combined use of creating CustomSerializer and using #JsonSerialize(using=CustomSerialzier) annotations at a class level.
public class CustomSerializer extends StdSerializer

Related

Different class types as RequestBody depending on RequestParam provided in a Spring Boot Controller?

So, I have a controller which takes in a request parameter and a body. The request body can be of various class types depending on the type of parameter. Currently I am using JsonNode for the body which works fine. Looks like this :
#PostMapping() public ResponseEntity<Response> save(#RequestParam("request type") RequestProcess process, #Valid #RequestBody JsonNode requestJson) {
I want to know whether it's possible to provide the body with the class type depending on the param provided. If yes how do I do it?
If this is not possible in REST, is there a chance I might be able to do this using GraphQl. I don't know much about GraphQL still researching.
TIA
The nearer you can reach is by using generics
class Controller < T > {
#PostMapping("/save")
ResponseEntity < Response > save(#RequestBody T requestJson) {}
}

#ModelAttribute vs #RequestBody, #ResponseBody

#ModelAttribute
RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method =
RequestMethod.POST)
public String processSubmit(#ModelAttribute Pet pet) { }
http://.../?name=Something&age=100
public String doSomething(#ModelAttribute User user) { }
#RequestBody
#RequestMapping(value = "/user/savecontact", method = RequestMethod.POST
public String saveContact(#RequestBody Contact contact){ }
{ "name": "Something", "age": "100" } in request body
public String doSomething(#RequestBodyUser user) { }
#ModelAttribute will take a query string. so, all the data are being pass to the server through the url
#RequestBody, all the data will be pass to the server through a full JSON body
Now which one is the best approach ???
If both are for same purpose to bind to the bean..which one is the best practice or widely used as standard practice?
Both handles multi-part file and does it both have equivalent options with one another ?
https://javabeat.net/spring-multipart-file-upload/
How do i upload/stream large images using Spring 3.2 spring-mvc in a restful way
Does any one of them has lesser capabilities then the other one? Like length limitations, method limitations. Drawbacks
Which one is more secured in terms of security ?
As the javadoc suggests, it's the usage that sets them apart, i.e., use #ModelAttribute if you want to bind the object back to the web view, if this is not needed, use #RequestBody
#RequestBody
Usecases : Restful controllers (ex: produce and consume json/xml, processing direct document download requests, searching for stuff, ajax requests )
As the name suggests the if a method argument is annotated with #RequestBody annotation Spring converts the HTTP request body to the Java type of the method argument.
Is only allowed on method parameters (#Target(value={ PARAMETER}))
The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request.
works for Post and not Get method.
#ModelAttribute
Usecases : web app controllers (ex: binding request query parameters, populating web views with options and defaults)
Uses data binders & ConversionService
Is allowed on methods and method params(#Target(value={METHOD, PARAMETER}))
Useful when dealing with model attributes for adding and retrieving model attributes to and from the Srping’s Model object
When used on METHODS, those methods are invoked before the controller methods annotated with #RequestMapping are invoked
binds a method PARAMETER or method return value to a named model attribute & the bound named model attributes are exposed to a web view
binds request query parameters to bean
For more information on Data Binding, and Type Conversion refer: https://docs.spring.io/spring/docs/5.1.x/spring-framework-reference/core.html#validation

POST / GET Request Param Validation in Spring Boot

I am using spring boot. I want to validated the POST request params. So I have gine through #Validated annotation but this require creating a different class for Every API. How should I write my code?
As for example, this is my api
#RequestMapping("/tags/{tagId}/{tagParentId}")
public Response<Demo> a(#PathVariable int tagId, #PathVariable int tagParentId){
... code
}
#RequestMapping("/data/{courseId}/{instId}")
public Response<Demo> b(#PathVariable int courseId, #PathVariable int instId){
... code
}
How should I change my code to add params validation for there API's such that I do not need to create two different validation class? Just one class and then I can add different functions for different API's.
#Validated should be used, to check that a parameter is syntactical correct.
As you are using int values, this is already done by spring.
If tagId is not a valid int, the client will already receive a Http error code.
The validation, whether there is a tag with the given tagId is implicitly done in your code, you do not need an additional validator for that.
If you read tags for example from the database, and you cannot find a tag for the tagId, you should
return new ResponseEntity(HttpStatus.NOT_FOUND);
from your controller method.
You may need to change the return type of your controller method to a common superclass or just to Object, to allow returning the ResponseEntity.
Its also possible to throw exceptions in the controller methods and to configure spring to return a regarding HttpStatus.
See exception-handling-for-rest-with-spring

getting null parameter values when I send body from rest client

Iam getting null parameter values when i send values from rest client. But when I send Values from form(html view page) it is working fine.
Below one is my bean class.
public class Home {
private String id;
And I am sending values from rest client as post method.
{
"id":"10",
"load":"true"
}
Content-Type: application/json
Request is coming to the controller class. but it will return all values as null .But when I am sending values from html page it is working fine. Any one can help how to get values.
When I am using #RequestBody in controller calss, I am getting Caused by: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported exception
The annotation #RequestBody should be added on Home homeRequest.
This allows the controller to analyze the request's body as the object's instance itself. This is the case of a JSON request.
Otherwise it is possible to use #RestController instead of #Controller as an annotation of the controller which does the same as #Controller, but it adds implicitly to all the request mapping methods the annotation #RequestBody to the inputs and #ResponseBody to all the response objects.

Read query string parameters in Spring REST API (POST)

My Spring REST API is decorated as follows:
In below, I am confused weather, parameters such as list, operation need to be part of Url as query string or do they need to be part of Request Body as form data (Url encoded).
There are situations where I am sending these parameters in query string and it works fine. But couple of my api's are not working properly on production and they work only if I send the data in request body as Url encoded. Can anyone help me explain this behaviour ?
#RequestMapping(value = "/bulkupdate/{companyId}", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity<String> bulkupdateArticle(#RequestParam("list") String documentIdList,
#PathVariable("companyId") String companyId, #RequestParam("operation") String operation){
try{
Looking at the resource I find that it could be better designed in a more REST-ful fashion. I don't like to see POSTed data in the reside in the url.
Next to becoming more Rest-ful it would also make live for you much easier.
I would create a Data Transfer Object and pass it as the body of the POST request to your resource/spring controller.
Going from your data:
public class ArticleToUpdate {
private String list; // list of what ? Maybe design it like List<String> somethingMoreMeaningFull
private String operation;
// .. getters
}
public ResponseEntity<String> bulkupdateArticle(#RequestBody ArticleToUpdate articleToUpdate) {
// .. do whatever you need with the posted data
Now you can post a JSON or XML document in the body which will probably life much easier.
Additionally you could also add validation on the posted data through #Valid support now.

Resources