How to propagate token using Spring Feign Client - java

I am using Feign Client to call another microservice as below:
#FeignClient("employee")
public interface EmployeeFeignClient {
#RequestMapping(
method= RequestMethod.GET,
value="/employee/code/{code}",
consumes="application/json"
)
EmployeeResponseEntity getEmployeeByCode(#PathVariable("code") String code);
}
The service which calls the employee service will have authentication bearer token in its request header. I need to pass this same token to the service call being made.
Tried to find on how to achieve the same but could not. Some help would be nice.

It was answered before.
The solution is to use #RequestHeader annotation instead of feign specific annotations
#FeignClient(name="Simple-Gateway")
interface GatewayClient {
#RequestMapping(method = RequestMethod.GET, value = "/gateway/test")
String getSessionId(#RequestHeader("X-Auth-Token") String token);
}

Related

Put request doesn't get to my controller by feign client, getting 415 status code

this is my feign client code
#RequestLine("PUT /merchants/{merchantId}")
#Headers("Content-Type: application/json")
MerchantDTO updateMerchant(#Param("merchantId") Long merchantId, PutMerchantDTO putMerchantDTO);
which is called in some requestFactory class.
And this one is my controller code
#PutMapping(value = "/merchants/{merchantId}")
ResponseEntity<MerchantDTO> updateMerchant(#RequestBody #NotEmpty PutMerchantDTO updateMerchantRequest, #PathVariable("merchantId") final Long merchantId) {
return ResponseEntity.ok(merchantUpdateMapper.toDtoMerchant(merchantUpdateService.processUpdate(merchantUpdateMapper.toDomain(updateMerchantRequest, merchantId))));
}
Can somebody Please tell me why I'm getting 415 when doing the put request with this feign Client to my controller?
remove #Headers
and in #PutMapping add consumes = "application/json"
#PutMapping(value = "/merchants/{merchantId}") you write the same line like you specified in feign client
and change #Param("merchantId") to #PathVariable("merchantId")

How to request Feign with Authentication JWT Bearer Java Spring?

I use two service in java spring service core and service shop, i want to insert data from service core with method in service core, but in service core i need to bearer token, how to i send auth bearer token from service shop to service core?
Implementing RequestInterceptor to set Authentication to request header.
public void apply(RequestTemplate template) {
if (RequestContextHolder.getRequestAttributes() != null && RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
String authorization = request.getHeader("Authorization");
if (StringUtils.isNotBlank(authorization)) {
template.header("Authorization", new String[]{authorization});
}
}
}
Naturally you need a way to obtain your service token from a well known OAuth endpoint using a client-credentials grant type
If you want to do it on a per integration basis, perhaps because you are integrating with different services using different approaches, you can do something like this:
#RequestMapping(method = [RequestMethod.GET], value = ["/id/{id}"], produces = [MediaType.APPLICATION_JSON_VALUE], consumes = [MediaType.APPLICATION_JSON_VALUE])
operator fun get(
#RequestHeader("Authorization") bearerToken: String = "Bearer mybiglongencodedtoken....",
#PathVariable("id") code: String,

RequestMapping: How to access the "method" value used for a rest endpoint

I have a Spring Boot REST controller endpoint that accepts both GET and POST requests:
#RequestMapping(
value="/users",
method= {RequestMethod.GET, RequestMethod.POST},
headers= {"content-type=application/json"}
)
public ResponseEntity<List<User>> getUsers() {
if(/*Method is GET*/) {
System.out.println("This is a GET request response.");
} else if( /*Method is POST*/) {
System.out.println("This is a POST request response.");
}
}
If this endpoint is hit with a GET request, I'd like for the controller to execute something in the appropriate if statement. whereas, if the endpoint is hit with a POST request, I'd like for the controller to take another course of action.
How does one extract this information from a rest controller? I'd rather not have to split this shared endpoint into two different methods. It's seems simple enough, I just can't find any docs on it.
The correct approach would be to rather map two separate GET and POST methods, but if you're set on doing this approach you can get the HTTP verb of the request by accessing the HttpServletRequest as follows:
#RequestMapping(
value="/users",
method= {RequestMethod.GET, RequestMethod.POST},
headers= {"content-type=application/json"}
)
public ResponseEntity<List<User>> getUsers(final HttpServletRequest request) {
if(request.getMethod().equals("GET")) {
System.out.println("This is a GET request response.");
} else if(request.getMethod().equals("POST")) {
System.out.println("This is a POST request response.");
}
}
You won't need to change your calling code, as the HttpServletRequest is automatically passed through
Just add two different methods with different names, one for the post and another for the get. Also, just leave the desired request method.
GET
#RequestMapping(
value="/users",
method= RequestMethod.GET,
headers= {"content-type=application/json"}
)
public ResponseEntity<List<User>> getUsers() {
System.out.println("This is a GET request response.");
}
POST
#RequestMapping(
value="/users",
method= RequestMethod.POST,
headers= {"content-type=application/json"}
)
public ResponseEntity<List<User>> postUsers() {
System.out.println("This is a POST request response.");
}
This way you don't add additional overhead and the code looks more clean.

Java check GET request info

I'm working with Facebook messenger app (chatbot) and I want to see what GET request I'm receiving from it. I'm using Spring Framework to start http server and ngrok to make it visible for facebook.
Facebook sending webhooks to me and i receive them, but i don't understand how to extract data from this request. Here what i get when I try HttpRequest to receive GET request. ngrok screenshot (error 500).
When I tried without HttpRequest, i had response 200 (ok).
What do i need to put to parameters of my find method to see GET request data?
My code:
#RestController
public class botAnswer {
#RequestMapping(method= RequestMethod.GET)
public String find(HttpRequest request) {
System.out.println(request.getURI());
String aaa = "222";
return aaa;
}
}
I guess HttpRequest will not help you here. For simplicity, just change HttpRequest to HttpServletRequest. You can access all query string parameters from it using request.getParameter("..."). Something like the following should work:
#RequestMapping(value = "/", method = RequestMethod.GET)
public String handleMyGetRequest(HttpServletRequest request) {
// Reading the value of one specific parameter ...
String value = request.getParameter("myParam");
// or all parameters
Map<String, String[]> params = request.getParameterMap();
...
}
This blog post shows how to use the #RequestParam annotation as an alternative to reading the parameters from HttpServletRequest directly.

How to handle json type request and xml type request using Spring RestTemplate

Some times I will get request as json(from rest client) format and some times xml(from form using jsp view) format. When i am written controller class as shown below, it will not allow request xml(from form using jsp view).
This is my problem. Controller class should allow both type of request.
#RequestMapping(value = "/home", method = RequestMethod.POST)
public String getCustomer(#RequestBody HomeRequest homeRequestequest,
HttpServletRequest request) {
String response = homeService.getCustomerResponse(homeRequestequest, request);
return response;
}
Please help how to resolve this issue. I am using 3.2.4.RELEASE version.
As jbarrueta said in comments, you need to declare 2 methods in Controller, e.g.
getCustomerJson and getCustomerXML.
The mappping for the first method would be :
#RequestMapping(value = "/home", method = RequestMethod.POST, consumes = "application/json")
and the mapping for the second method would be:
#RequestMapping(value = "/home", method = RequestMethod.POST, consumes = "application/xml")

Categories

Resources