Spring and WSO2 Identity Server - SCIM2.0 API for User CRUD - java

I'm implementing an application with Spring Boot. From the application some users will have the permission to create, update, delete other users. To do so I'm using WSO2 Idenity server SCIM 2.0 APIs.
When I try with postman to call for example this api: POST localhost:9443/t/carbon.super/scim2/Users
to create a new user and i pass all the required information:
Access token, generated with the command:
curl -L -X POST 'localhost:9443/t/carbon.super/oauth2/token' -H 'Authorization: Basic clientid:clientsecret' -H 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'grant_type=password' --data-urlencode 'username=manager' --data-urlencode 'password=manager' --data-urlencode 'scope=internal_user_mgt_create'
clientid
clientsecret
scope (internal_user_mgt_create)
it works, but now I have to implement it in java.
So I created a UserController and I implemented this:
#PostMapping("https://localhost:9443/t/carbon.super/scim2/Users")
public ResponseEntity<Void> createUser(#RequestBody CreateUserRequest createUserRequest) {
HttpHeaders headers = new HttpHeaders();
String plainCreds = clientId:clientSecret;
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
headers.add("Authorization", "Basic " + base64Creds);
headers.add("Content-Type", "application/x-www-form-urlencoded");
return ...;
}
how do I specify in the header these other things:
--data-urlencode 'grant_type=password'
--data-urlencode 'username=manager'
--data-urlencode 'password=manager'
--data-urlencode 'scope=internal_user_mgt_create'

The values that you have mentioned are for the token call right? In that case these does not need to be in the header of the request. You should have them as the request body.
Once you get the token from the oauth2/token you can use it to invoke the SCIM APIs. Following is a sample API call to invoke user creation with a bearer token.
curl -L -X POST 'https://localhost:9443/scim2/Users' -H 'Content-Type: application/json' -H 'Authorization: Bearer 15b93905-68b2-3377-b77b-9bd1968d7ff9' --data-raw '{
"schemas": [],
"userName": "somindaRest",
"password": "somindaRest"
}

Related

Missing request header 'client_id' for method parameter of type String

While doing a post request to the Spring Boot Rest API it is throwing Servlet Request Binding Exception with error message "Missing request header 'client_id' for method parameter of type String". Even after passing the client_id field in header.
It is happening in only one of our testing env. where request header is containing "_" underscore in its name. Same code is working in local. What could be the issue here. Is it something related to deployment file or code related issue.
curl --location --request POST 'http://localhost:7087/test' \
--header 'accept: application/json' \
--header 'client_id: test' \
--header 'Content-Type: application/json' \
--data-raw '{
"data": "test"
}'
#PostMapping(path = "/test", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Object pushMsg(#Valid #RequestBody String data,
#RequestHeader("client_id") String clientId) {
return null;
}

Unable to have a method with application/json or multipart/form-data in SPRING java

I'm trying to create a method that either receives a JSON or a .csv file in order to populate a database. It goes like:
#RequestMapping(method = RequestMethod.POST,
consumes = {"multipart/form-data","application/json"})
public ResponseEntity<PeopleResponse> create(
#RequestBody People PeopleDTO,
#RequestParam(name = "csvFile", required = false) MultipartFile csvFile,
HttpServletRequest request)
When I try it with Postman with a json sending:
curl --location --request POST 'localhost:9001/people' \
--header 'Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJtcmVnYWxhZG8iLCJhdXRob3JpdGllcyI6eyJsb2dpbiI6IjEiLCJnb2RNb2RlIjoiMSIsInJlZ2lzdGVyIjoiMSJ9LCJzYWx0IjoxNTg5NTg2ODgwMzI1LCJzb3VyY2UiOiJsb2NhbGhvc3QifQ.DrdUC7JN-Db0-_6qNGn9i5n3YzVopGNisecLy08SvMCudmveZnwATRwMftf2VKBZqhUKdQIrJGsNXudU1uwTgA' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "Homer",
"age": 25
}'
It works, but when I try it sending a csv file with Postman, it fails:
curl --location --request POST 'localhost:9001/people' \
--header 'Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJtcmVnYWxhZG8iLCJhdXRob3JpdGllcyI6eyJsb2dpbiI6IjEiLCJnb2RNb2RlIjoiMSIsInJlZ2lzdGVyIjoiMSJ9LCJzYWx0IjoxNTg5NTg2ODgwMzI1LCJzb3VyY2UiOiJsb2NhbGhvc3QifQ.DrdUC7JN-Db0-_6qNGn9i5n3YzVopGNisecLy08SvMCudmveZnwATRwMftf2VKBZqhUKdQIrJGsNXudU1uwTgA' \
--form 'csvFile=#/home/myself/Downloads/people.csv' \
It gives me the following error:
2020-10-05 15:09:20.602 WARN 13086 - [nio-9001-exec-3] s.w.s.h.AbstractHandlerExceptionResolver | Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=--------------------------276557520366487467828532;charset=UTF-8' not supported]
I'd like to know if it's possible to have either application/json or multipart/form-data in one method or if the only way is to make two separates methods (Though it ruins a little the naming, because second method would be like "POST people/by-file"

How we can add the request parameter in with url in swagger tool

I want to customize the input text box in swagger ui and test the rest service ,but while sending the request parameter in input text box the request parameter is not appended with service ulr ,
for example
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' 'http://localhost:8765/COMMONAPI/V2.0/gameList' the piece of request param is not added and due to this I am getting null pointer exception
enter image description here
enter image description here
I want exact request as below
curl -X POST "http://localhost:8765/COMMONAPI/V2.0/gameList" -H "accept: application/json" -H "Content-Type: application/json" -d "{ \"timeStamp\": \"2019-03-18T05:11:15\", \"hashKey\": \"c0849bbf6eb17e48a72b92aa8f67650f\", \"apiKey\": \"72uyhsu87sf3\", \"apiId\": 6, \"sessionKey\": \"SdPpZI4LFTlux\"}"
In you SwaggerConfiguration you can define globalOperationParameters for passing paramaters. Something like below.
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.globalOperationParameters(Arrays.asList(new ParameterBuilder()
.name("token")
.description("Authentication token obtained after authentication.")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(true)
.build()))
.select()
.apis(RequestHandlerSelectors.basePackage("com.mypackage"))
.build();
}

How can i get params in spring from curl -X request?

I have a problem with processing params from curl request to my spring-boot app.
My controller post method:
#RequestMapping(value = "/cat", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity addCat(#Valid #ModelAttribute NewCatRequest newCatRequest, BindingResult bindingResult) {
System.out.println( newCatRequest);
if (bindingResult.hasErrors()) {
return ResponseEntity.badRequest().body(bindingResult.getFieldError().getDefaultMessage());
}
int rowsAffected = catsRepository.saveCat(newCatRequest.getName(), newCatRequest.getColor(), newCatRequest.getTail_length(), newCatRequest.getWhiskers_length());
if (rowsAffected == 1) {
return ResponseEntity.ok().body(newCatRequest);
} else {
return ResponseEntity.badRequest().body("There was an unexpected error while trying to create cat for you :(");
}
}
And the problem is: when i'm trying to send this with curl:
curl -X POST http://localhost:8080/cat \
-d "{\"name\": \"Tihon\", \"color\": \"red & white\", \"tail_length\": 15, \"whiskers_length\": 12}"
I have all null params in 'newCatRequest':
NewCatRequest{name='null', color='null', tail_length=0, whiskers_length=0}
BUT when i'm trying to do the same with Postman (POST method, x-www-form-urlencoded in body with my params) i have a valid result:
Result from Postman
Help me pls to understand what's the problem.
curl -X POST http://localhost:8080/cat \
-d "{\"name\": \"Tihon\", \"color\": \"red & white\", \"tail_length\": 15, \"whiskers_length\": 12}"
The above curl request has a JSON body, whereas your request processing method
#RequestMapping(value = "/cat", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
consumes/accepts: application/x-www-form-urlencoded. Therefore, you should either convert your method to consume/accept application/json or change your curl request to:
curl -X POST http://localhost:8080/cat \
-d 'name=Tihon&color=red%20%26%20white&tail_length=15&whiskers_length= 12' \
-H 'Content-Type: application/x-www-form-urlencoded'
EDIT 1
Please note that the default Content-Type for curl is application/x-www-form-urlencoded. To use JSON, change your request to:
curl -X POST http://localhost:8080/cat \
-d "{\"name\": \"Tihon\", \"color\": \"red & white\", \"tail_length\": 15, \"whiskers_length\": 12}" \
-H 'Content-Type: application/json'
Try this:
curl -X POST \
http://localhost:8080/cat \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'name=Thidon&color=red%20%26%20white&tail_length=15&whiskers_length=12'
You forgot the header application/x-www-form-urlencodedand the body should not be in json format.
you can use the code option below send button in postman to generate the exact curl request which will work for you https://i.stack.imgur.com/hbk8M.png
in code drop down menu search for curl and it will generate a neat and clean curl request for you .
Hope this helps

How to send list using curl?

The backend is coded like this:
#POST
#Path("/resource")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response dailyBilling(
final List<String> students)
throws Exception {
....
}
How should I send curl data, which would me accepted as a List on backend ?
Using the following curl i get 400:
curl --digest -u ameya379+beet#gmail.com:credentials\
-H 'Content-Type: application/json'\
-X POST -d '{"student1", "student2"}'\
http://localhost:8080/api/somepath/resource
Error:
{
"detail":"Received JSON does not match expected format.",
"error":400,
"errorCode":"INVALID_JSON",
"parameters":[],
"reason":"Bad Request"
}
Arrays are encoded between [] in JSON.
curl --digest -u ameya379+beet#gmail.com:credentials -H 'Content-Type: application/json' -X POST -d '["student1", "student2"]' http://localhost:8080/api/somepath/resource

Categories