I am creating an application using spring mvc, in all of my application i have written the methods using #Request Mapping in the following manner:
#RequestMapping(value = "/txnMst/{portNumber}", method = RequestMethod.GET)
As you can see that in the request mapping i am passing the portNumber which is displayed later in the URL like this (portNumber is 3333 in the example):
http://localhost:8080/admin/txnScript/txnMst/3333
Now i want to hide these data i.e the portNumber, is there any way how i can achieve this.
Please provide some help.
If the client doesn't need this data why are you storing it in URL? An alternative place to store that data is in the session.
Storing server values in client, expecting that them will be returned unaltered is a bad idea.
Related
Objective
When a person creates a resource (no need to connect), she receives a unique token, which she must then transmit to each request she sends for information about her resource.
Question
There is a simple way to do that with Spring? Indeed, all tuto I found and read used an authentification with username and password.
Already tried
My first idea was to create a token at the end of POST methods (store it into database), put it into each GET requests and check if requestToken == databaseToken.
However, I don't think that's the best way to do it.
So, can you help me and advise me to solve the problem?
Thanks a lot!
There are multiple ways.
Using the #SessionAttributes annotation:
The first time our controller is accessed, Spring will instantiate an instance and place it in the Model. Since we also declare the bean in #SessionAttributes, Spring will store the instance.
You will get it inside controller's handler method thru #ModelAttribute.
Or, you can try this route:
#RequestMapping(value = "/test")
public String handler(HttpSession httpSession) {
httpSession.getId(); //this will give you unique identifier that you can set back to object that you send to front end and can share the same ID between requests.
}
https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSession.html#getId--
I hope someone will be able to help me understand how to create an endpoint HTTP server listener. I'm trying to create a POST request handler that can save all post requests made to a text file.
The purpose is for a Game state integration between My application and Counter-Strike. Ive read their documentation (csgo GSI documentation) and the example given in here is almost exactly what I'm looking for. But its written in nodejs and I will need it to work with Java.
I have only been able to create a HTTPServer but can't seem to understand how I can create a POST request handler which records the data sent to "data" request.
How can I create a handler which can record all requests sent to data?
I believe the easiest & fastest way is to grab a SpringBoot app from https://start.spring.io/ (add Web dependency). And then create a Spring #RestController like that:
#RestController
#RequestMapping(value = "/cs")
public class CsController {
#RequestMapping(value = "", method = RequestMethod.POST)
public void processCsData(#RequestBody CsData csData) {
processCsData(csData);
}
}
where CsData is a POJO class that they send to you. processCsData() is your method to do whatever you like with the data.
Now you need to host it somewhere so that it would be reachable from the Internet or you can use https://ngrok.com/ to create a tunnel for test purposes.
I am currently working on a monitoring application using Spring Cloud Sleuth. Currently I try to collect as much information about my requests as possible.
To keep the approach as scalable as possible I use GenericFilterBeans and HandlerInterceptorAdapter to access information from the requests sent to the REST-API.
I am struggling with getting parameters of a REST-call where the parameters are mapped from the URL like in the following code snippet:
#RequestMapping(
value = {"/{service}/{route_id}/book", "/accounting-core-service/{service}/{route_id}/book"},
method = RequestMethod.GET)
#ResponseBody
public ModelAndView book(#PathVariable(value="service") String serviceName,
#PathVariable(value = "route_id") int routeId,
HttpServletResponse response) {
/*Do something*/
}
The question is not, whether it is good practice or not to write it like so. The question is whether there is an approach similar to Filter or Interceptor (or the proper use of them) to access those parameters.
A requirement is, that it can be applied easily to an application by adding very few lines of code. Annotating every Method call manually or manually inserting the code to write the parameters into the trace from within the method is not feasible for me.
If you need more information feel free to ask. I will provide you with all information you need to help me with my problem.
Although not officially supported (as it's not written in the reference documentation), Spring MVC holds that information as request attributes.
You could create your own HandlerInterceptor, ordered right after the Sleuth one, and get that information from the request like this:
// "/{service}/{route_id}/book"
String matchingPattern = (String) request
.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
// "service" => "fooService", "route_id" => "42"
Map<String, String> templateVariables = (Map<String, String>) request
.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
Note, the template variables are already decoded at that point, which is probably what you want anyway.
You can create a Filter that intercept all the requests.
For each request you can retrieve also this informations:
query parameters
body of request
url
header parameters
You can save all this data as you need.
This is the best way you can do that.
If you need to group all urls like /{service}/{route_id}/book in a "family" of urls you can do that splitting the url and check if it is part of the family, but when a new family is added in your code you need to update the filter (or configure something in an external file or database).
I am working on an internal tool that simulates SOAP responses for different web services that our product uses. This is intended for use in local development.
The idea is to store the SOAP responses in the database as a blob data. During the mapping of a URL keys to a response, the URL keys and expected SOAP response will be stored to the database. The simulated SOAP response will be as a string body in POST request.
The SOAP response will be stored as a blob in the database along with URL keys. If the URL is /configureresponse/{responsetype}/{responsecode}/, then the values of response type and response code will be saved to the database along with the SOAP response as string.
I am building a Spring MVC application for the same. The code snippet is given below
#Controller
#RequestMapping(value = "/configureresponse/{responsetype}/{responsecode}",
method = RequestMethod.POST)
public ModelAndView configureResponse(
#PathVariable String responseType, #PathVariable String responseCode,
#RequestBody String soapResponse) {
}
How do I return a Servlet Response such as 200 OK or 403 Forbidden based on certain conditions?
Is there a way to secure the incoming XML response and the outgoing XML response? This is an internal tool, but I am not sure how to handle XML injection or any other security issues.
UPDATE: How do I secure the application against a billion laughs attack or make it more secure?
Should I be checking for XSRF vulnerability? If yes, how do I do that?
How do I handle simultaneous concurrent inputs for the same response and request?
UPDATE: How do I check if say one thread is updating the response for a given response type and response code, while the other thread is viewing the response for a given response type and response code?
How do I return a Servlet Response such as 200 OK or 403 Forbidden based on certain conditions?
There are several ways to do this. For instance, you could change your return type to a ResponseEntity<String>, which has a constructor that accepts an HttpStatus. Or, you could simply pass in an HttpServletResponse and set the response code there. Knowing Spring, there are probably 20 more valid ways to do this. I would suggest reading through the excellent Reference Guide available on their site.
Is there a way to secure the incoming XML response and the outgoing XML response? This is an internal tool, but I am not sure how to handle XML injection or any other security issues.
Not sure what you mean by "secure". If you mean transmission, then use SSL. If you mean authorization/authentication use Spring Security. If you mean something else, then I am not sure what to offer except to say I need a better explanation of what you want/need.
Should I be checking for XSRF vulnerability? If yes, how do I do that? Any link or tutorial would be welcome.
Security should be a concern, whether it's an internal app or external. Most hacks now-a-days are done by social engineering their way into the intra-net of a company. Take the recent Target breach. I believe they used the AC repair service to gain access to the building. I went to a Schmoocon talk once where a guy hired to test a companies' security actually got a job as a janitor and would plug in a Linux device he built, go mop some floors, then pick up the device which had scanned all their internal networks. So, yes, if you believe you should guard against an attack, then I would say do so.
How do I handle simultaneous concurrent inputs for the same response and request?
Not sure what you mean by this. Spring MVC typically uses session to isolate requests. If two different users request the same thing, they are two different requests for the same thing. I would suggest using some caching so that you are not hitting your DB every time, but other than that I see no problem.
I am creating a simple RESTful web service with simple types successfully. Now I want to pass an object as argument for web service and get the object as response. My scenario is, Parse the XML message as object by using Jaxb and send the object as request for web service. After that in server side it process the requested object and generates the response xml file and send back it as object.
In URL path i give
"http://localhost:8080/SampleWS/rest/checkXML/username=visolve&password=visolve"
for simple type. But in object I don't know how to give the object reference in URL. Please help me how to solve my problem..
Regards
Bathakarai
Just define a very good-looking domain object. JAXB and JAX-RS will do the rest.
JAXB.
#XmlRootElement
class Regards {
#XmlElement
private long sincerely;
}
JAX-RS.
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#POST
#Path("/sincerely")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response sincerely(final Regards regards) {
regards.setSincerely(System.currentTimeMillis());
return Response.ok(regards).build();
}
Though you could certainly include the entire XML content in your URL, I would probably shy away from it.
Think of it this way: if you encode the XML in the URL you're potentially adding more work on both ends. Now the server and client will both need to know how to build the URL properly, and check to make sure everything lines up correctly. What if, in the future, you need to offer a JSON or YAML view of the same content? Now your URL might need to include the content-type as well. What about character-encoding?
All this to say, HTTP provides a terrific transport mechanism which already addresses these concerns. Include the XML as the entity body of the HTTP message, and use the HTTP header to identify what content-type you're sending, character-encoding, etc. This will work both ways (the server and client both can send the XML back/forth), and makes better use of HTTP.
Here's a related link which might help with some of the details. And another.
On a side note, please, please, please tell me you don't plan on sending user-credentials in plain text across an unencrypted link.