Spring throwing 403 exception on POST request but POSTMAN request working - spring

I am trying to POST some data to rest api, When I send the request to API using SPRING REST I get the 403 exception.
I have tried adding user-agent header as suggested by other answers but nothing has worked for me so far. I also checked that access key when using POSTMAN and when calling the service is same. Any advice would be helpful;
The wrapper class to create the body of POST request
public class ApiRequest implements Serializable {
private static final long serialVersionUID = 3729607216939594972L;
#JsonProperty("id")
List<Integer> id;
#JsonProperty("sdate")
String sdate;
#JsonProperty("edate")
String edate;
#JsonProperty("fields")
List<String> fields;
public ApiRequest(List<Integer> id, String sdate, String edate, List<String> fields){
this.id=id;
this.sdate=sdate;
this.edate=edate;
this.fields=fields;
}
public void setEdate(String edate) {
this.edate = edate;
}
public void setSdate(String sdate){
this.sdate=sdate;
}
public void setFields(List<String> fields) {
this.fields = fields;
}
public void setId(List<Integer> id) {
this.id = id;
}
public String getEdate() {
return edate;
}
public String getSdate() {
return sdate;
}
public List<String> getFields() {
return fields;
}
public List<Integer> getId() {
return id;
}
#Override
public String toString() {
return "ApiRequest{" +
"id=" + id +
", sdate=" + sdate +
", edate=" + edate +
", fields=" + fields+
'}';
}
}
Code to call the api
private HttpHeaders getRequestHeaders() {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
requestHeaders.setAccept(Arrays.asList(MediaType.ALL));
requestHeaders.set("user-agent","Some User Agent);
requestHeaders.set("access_token", "ACCESS_TOKEN");
return requestHeaders;
}
ApiRequest request=new ApiRequest(Arrays.asList(10),DateUtil.today().toString(),DateUtil.today().plusDays(10).toString(),Arrays.asList("ALL"));
String response=post("RANDOM_URL",null,null,request,getRequestHeaders(),String.class,"");
Post super method:
public <T> T post(String baseUrl, String url, String query, Object body, HttpHeaders requestHeaders, Class<T> responseClassType, String logTag) {
// In this method body is converted to Json String and called the restExchange

If you are sure that with Postman you are getting correct results then you can enable debug logs for the underlying httpclient ( if apache http client is the underlying http library) by setting logging.level.org.apache.http=DEBUG. This will print all the request details like url, headers etc by which you can compare with what you are sending with Postman. If the client library is something different then you may need to write an interceptor to capture all the request details as explained here.

Related

How to correctly handle exceptions from the service (spring boot rest)

When building a rest api using spring boot what is the best way to handle exceptions from the service level and pass them to the controller, so the client gets a custom json error message.
{
"message": "some error"
}
Endpoint from controller
#PostMapping("/login")
public String login(#RequestBody #Valid LoginDto loginDto) {
return gson.toJson(userService.login(loginDto.getUsername(), loginDto.getPassword()));
}
Service level code
public LoginResponseDto login(String username, String password) {
try {
//performs some checks
...
return new LoginResponseDto(token.get());
} catch (AuthenticationException e){
LOGGER.info("Log in failed for user {}", username);
}
return new LoginResponseDto("login failed");
}
LoginResponseDto class
String token;
String message;
public LoginResponseDto(String message) {
this.message = message;
}
Currently it is obviously returning the correctly message but not the correct status code, it will show status 200 with the error message in json.
You have some options:
1) Returning a message:
If you want to return a message something like this,
{
"message": "some error"
}
What you can do is:
Option 1: Create a custom POJO class for error message and return the reference to the object of that POJO class.
Something like this:
ErrorMessage.java
package org.example;
public class ErrorMessage {
private String message;
public ErrorMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Request Handler Method in Controller:
#GetMapping("/login{?username, password}")
public ErrorMessage isUserAuthenticated(#RequestParam String username, #RequestParam String password) {
if (username.toLowerCase().contentEquals("root") && password.contentEquals("system")) {
return new ErrorMessage("authenticated");
}
return null;
}
Option 2: Create a Map and insert key-value pairs that you want to have in the message.
Like this:
#GetMapping("/login{?username, password}")
public Map<String, String> isUserAuthenticated(#RequestParam String username, #RequestParam String password) {
Map<String, String> message = new HashMap<>();
if (username.toLowerCase().contentEquals("root") && password.contentEquals("system")) {
message.put("message", "authenticated");
}
return message;
}
2) Returning an error status code (highly recommended by me):
You may use ResponseEntity for this purpose.
#GetMapping("/login{?username, password}")
public ResponseEntity<?> isUserAuthenticated(#RequestParam String username, #RequestParam String password) {
if (username.toLowerCase().contentEquals("root") && password.contentEquals("system")) {
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

Spring Rest Api Design For Following a User in Twitter Clone Appliction?

I Want to Design a Demo Twitter Clone Application where user can follow any other user . however i am doubting my rest api design . please suggest me am i right .
Can I pass followerId in url rather than passing it as requestbody as we already know followerId in Advance and server does not create followerId here ?
and if better option could be there like put/patch or any rest api design ?
Please suggest me better design if possible
Here JwtUser is Authenticated User
public class FollowerDto {
private Long followerId;
private boolean following;
public FollowerDto() {
}
public FollowerDto(Long followerId, boolean following) {
this.followerId = followerId;
this.following = following;
}
public boolean getFollowing() {
return following;
}
public void setFollowing(boolean following) {
this.following = following;
}
public Long getFollowerId() {
return followerId;
}
public void setFollowerId(Long followerId) {
this.followerId = followerId;
}
}
#PostMapping("/follower")
#ResponseStatus(HttpStatus.CREATED)
public StatusDto addFollower(#RequestBody #Valid final FollowerDto
followerDto, #CurrentUser final JwtUser user, final
HttpServletResponse response) {
RestPreconditions.checkRequestElementNotNull(followerDto);
RestPreconditions.checkArgumentCondition(followerDto.getFollowing());
return userService.addFollower(user, followerDto.getFollowerId(),
response);
}
// Service Layer
#Override
public StatusDto addFollower(final JwtUser jwtUser, final Long followerId, final HttpServletResponse response) {
final User follower = userRepository.findById(followerId).orElse(null);
ServicePreconditions.checkEntityExists(follower, "Follower does not exist with id " + followerId);
final User currentUser = userRepository.findByEmail(jwtUser.getEmail());
if (currentUser != null) {
ServicePreconditions.checkOKArgument(!currentUser.equals(follower));
final Set<User> existingFollowers = currentUser.getFollowers();
if (existingFollowers != null) {
existingFollowers.add(follower);
} else {
currentUser.setFollowers(Sets.<User>newHashSet(follower));
}
userRepository.save(currentUser);
final URI uri = ServletUriComponentsBuilder.fromCurrentRequestUri().path("/{idOfNewResource}").buildAndExpand(follower.getId()).toUri();
response.setHeader(HttpHeaders.LOCATION, uri.toASCIIString());
return new StatusDto("Follower Added Successfully to user having email " + jwtUser.getEmail());
}
return new StatusDto("Follower is not Added to user with email " + jwtUser.getEmail());
}

Can spring map POST parameters by a way other than #RequestBody

I am using #RestControllers with an application where all requests are POST requests ... As I learned from this post , you can't map individual post parameters to individual method arguments, rather you need to wrap all the parameters in an object and then use this object as a method parameter annotated with #RequestBody thus
#RequestMapping(value="/requestotp",method = RequestMethod.POST)
public String requestOTP( #RequestParam(value="idNumber") String idNumber , #RequestParam(value="applicationId") String applicationId) {
return customerService.requestOTP(idNumber, applicationId);
will not work with a POST request of body {"idNumber":"345","applicationId":"64536"}
MY issue is that I have A LOT of POST requests , each with only one or two parameters, It will be tedious to create all these objects just to receive the requests inside ... so is there any other way similar to the way where get request parameters (URL parameters) are handled ?
Yes there are two ways -
first - the way you are doing just you need to do is append these parameter with url, no need to give them in body.
url will be like - baseurl+/requestotp?idNumber=123&applicationId=123
#RequestMapping(value="/requestotp",method = RequestMethod.POST)
public String requestOTP( #RequestParam(value="idNumber") String idNumber , #RequestParam(value="applicationId") String applicationId) {
return customerService.requestOTP(idNumber, applicationId);
second- you can use map as follows
#RequestMapping(value="/requestotp",method = RequestMethod.POST)
public String requestOTP( #RequestBody Map<String,Object> body) {
return customerService.requestOTP(body.get("idNumber").toString(), body.get("applicationId").toString());
I have change your code please check it
DTO Class
public class DTO1 {
private String idNumber;
private String applicationId;
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
public String getApplicationId() {
return applicationId;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
}
Rest Controller Method
#RequestMapping(value="/requestotp",method = RequestMethod.POST)
public String requestOTP( #RequestBody DTO1 dto){
System.out.println(dto.getApplicationId()+" (------) "+dto.getIdNumber());
return "";
}
Request Type -- application/json
{"idNumber":"345","applicationId":"64536"}
OR
#RequestMapping(value="/requestotp",method = RequestMethod.POST)
public String requestOTP( #RequestBody String dto){
System.out.println(dto);
return "";
}

Spring Service and RestTemplate Client always Unexpected end of file from server

My POJO:
public class Product {
String name;
int price;
public Product(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
My Controller:
#RestController
#RequestMapping("/rest")
public class RstController {
#RequestMapping(value = "/getProductPost2", method=RequestMethod.POST, produces = {"application/json"})
public Product getProductPost2(#RequestBody Product p){
System.out.println(p.getName());
return p;
}
My Client, using JUnit(I've tried all the lines commented, the same error everytime):
public class RestTemplatePostTest {
#Test
public void testee(){
String url = "http://localhost:8443/ShoppingCartSpringMVCSpringDataHibernate/rest/getProductPost2";
Product p = new Product();
p.setName("produs");
p.setPrice(22);
String json = "{\"name\":\"pen\",\"price\":10}";
HttpEntity<Product> request = new HttpEntity<Product>(p);
RestTemplate rt = new RestTemplate();
rt.postForObject(url, json, String.class);
//rt.postForObject(url, p, String.class);
//rt.exchange(url, HttpMethod.POST, request, Product.class);
//rt.exchange(url, HttpMethod.POST, request, String.class);
//assertEquals("produs",p2.getName());
}
}
When I'm using POSTMAN, it works.
I haven't found any other option on the internet and it's been 2 days since I'm trying to do this . Any opinion or tutorial is more than welcomed.
Edit1: Also, a simple GET also doesn't work,but it works in browser or in POSTMAN.
#RequestMapping(value = "/getProductGet", method=RequestMethod.GET)
public String getProductGet{
return "hello World!!";
}
#Test
public void testGet(){
String url = "http://localhost:8443/ShoppingCartSpringMVCSpringDataHibernate/rest/getProductGet";
RestTemplate rt = new RestTemplate();
ResponseEntity<String> response= rt.getForEntity(url, String.class);
}
When in debug mode, it stops in my breakpoint when called by browser or POSTMAN, but it doesn't get there when using rest template.
Perhaps something to do with the fact that I'm using Spring security?
I think the problem is that your request has a wrong data type which server can not parse and thus can not reply.
Since you are sending a POST request with JSON Content-Type, your Product must be JSON-encoded.
To do that, you need to add a json converter so modify your code to some thing like this:
RestTemplate rt= new RestTemplate();
rt.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Product recievedProduct = rt.postForObject(url, p, Product.class);
Don't forget to add the jackson dependency.

FeignClient: Serialize RequestParam to JSON

I have a spring boot application in which I am trying to use Feign to communicate with a remote service. My #FeignClient is defined as follows:
#FeignClient(name="TEST_SERVICE", url="URL")
#Component
public interface SomeServiceClient
{
#RequestMapping(
method = RequestMethod.POST,
value = "/someService",
consumes = "application/json",
produces = "application/json"
)
SomeServiceResult getServiceResult(
#RequestParam(value = "mode") String mode,
#RequestParam(value = "payload") SomeServicePayload payload
);
}
I would like the payload object of type SomeServicePayload to be serialized into JSON. I expected this to happen automatically, but it does not. Instead, payload is serialized to its fully qualified class name.
Do I need to set a custom encoder/decoder combination for this client? How would I do this?
#FeignClient under the hood used toString() method for bulding request string. The easiest way to create proper request is to override toString() method manually:
class SomeServicePayload{
String payload;
#Override
public String toString() {
return "{\"payload\":\"" + payload + "\"}";
}
}
Or for complex objects by using ObjectMapper:
public class SomeServicePayload{
private String payload;
public String getPayload() {
return payload;
}
public void setPayload(String payload) {
this.payload = payload;
}
private ObjectMapper mapper = new ObjectMapper();
#Override
public String toString() {
try {
return mapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
//...
}
return null;
}
}

Resources