Is there a common way to secure a pathvariable?
#RequestMapping("/image/{id}")
public String getArticleImageUrl(#PathVariable String id) {
....
I mean remove unusual content e.g. javascript or other security issue related things to prevent "hacking" or abusive use?
What is secure depends on what you want to use the input for. Bottom line: You should take the same care with these kinds of parameters as any other parameter you would accept from the outside into the system, e.g.:
Take appropriate action to prevent SQL injection (i.e. PreparedStatements)
Take care when rendering stuff on your web site that was received as user input (i.e. make sure to HTML encode stuff - most frameworks would take care of this for you).
etc.
"Washing" the input from unwanted characters is possible but, as always: tricky and depending on what the data will be used for.
Nvm.
I used a regex to check if this String is alphanumeric. ( ^[\\pL\\pN]+$ )
Should be enough.
Related
I have a Java based back end in which I'm using Hibernate for some more specific bean validation, namely: #SafeHtml. It works great for 99% of my needs, however I have an part which allows a user to enter basic HTML to create their own page and I need to be less restrictive here.
My problem is that I want to restrict certain types of HTML elements (i.e. '' tags etc...), while allowing attributes for the HTML elements I deem appropriate (i.e. ) . As far as I've been able to see, #SafeHtml doesn't allow any attributes unless explicitly defined like the following:
#SafeHtml (
whitelistType = WhiteListType.RELAXED,
additionalTagsWithAttributes = {
#Tag(name = "div", attributes = {"class", "style"},
#Tag(name = "anotherTag", attributes = {"id", "anotherAttribute"}
}
)
Hopefully, you can see the problem with this, to allow even a small subset of tags, with their attributes enabled, would be incredibly verbose and wasteful, not to mention it would be easy to miss something with all the tags and attributes out there.
So... my question is: Is there a better way to do this? It seems like it shouldn't be that unique of a situation: i.e. you want to validate user input that's HTML, but only want to reject script tags...
And none of the other WhiteListType types suites you better? If not and you think the configuration of #SafeHtml is to cumbersome, you can always hand-roll your own #MySafeHtml. This custom constraint could under the hood also use JSoup or any other way you think is appropriate for your particular use-case.
I have a url say /prefix/part1/part2/.../partN/suffix and in a controller i want to map anything between /prefix/ and /suffix to one variable.
Approaches tried
#RequestMapping(value = "/prefix/{store:[\s\S]*}/suffix",
method = RequestMethod.GET)
Also, tried regex : (.*), The interesting part is i don't know what N is. So, cant explicitly specify number of slashes possible.
I have an open JIRA issue requesting this ability, but the Spring core team apparently doesn't think that it's useful and is not interested in supporting it. You might make a note there.
In the meantime, the only option is to get the entire string from the request and parse it yourself.
Play, I understand, seperates answers to a request in two layers: The controller method puts all the data together, the view actually creates the output.
I have a function "get customer list". The controller creates, say, a List. Now, what I want is to have two outputs of this controller's result:
1) I want the usual HTML output, so a controller which prints
...<table><tr><th>Name</th>...</tr>
<tr><td>Smith</td>...</tr>
...
</table>...
2) From the same List, I would also create a JSON (or CSV or XML) file containing the customer data as JSON information.
From how I understand Play, it should be possible to obtain this by putting another view renderer at the end of the controller. I would have two URLs, say
/customer/list.html
and
/customer/list.json
which return the two differently formatted results but which use the same controller (which btw. is implemented in Java).
Can this be done? How can this be done? Or is my approach not sensible?
Best regards,
Dirk
I'm a bit reluctant to answer here since I'm unsure about the Play Java stuff, but you could take two approaches:
have a route specified for every format you support (differing on .json, .html etc)
parameterise the suffix and response differently in the action depending on it's value.
Suppose you support both HTML and JSON output (with HTML the default.) You could define a single route like this:
GET /customer/list$format<(\.(:?html|json))?> controllers.Application.renderMyList(format: String)
(Note: the .type suffix is optional, you could have /list.html or /list.json or just /list. Read up about regex dynamic route parameters here.)
Your action might look like this:
public static Result renderMyList(String format) {
List<Something> myList = getMyList();
if (format.equals(".json") {
Ok(convertToJson(myList));
} else {
Ok(views.html.myList(myList));
}
}
On the other hand you could explicitly define two routes pointing to the same action, with different fixed parameters:
GET /customer/list.html controllers.Application.renderMyList(format: String = ".html")
GET /customer/list.json controllers.Application.renderMyList(format: String = ".json")
But I think the first option is more succinct and generally nicer.
NB: I think for this kind of content-dependent stuff it's generally better to use content negotiation instead of different URLs. You can read up on that here.
Scenario
A web service receives a request in the form of XML from some other system, based on the contents of this request the web service should perform an arbitrary number of user-definable tasks (such as storing the contents of the XML to a database, extracting certain values, making a call to some other service etc). The behaviour of the requesting system cannot be changed (e.g. to call different actions for different things).
Proposed Design
My proposed design would be to have an interface something like...
interface PipelineTask {
public void Run(String xml);
}
With implementations of this for each user action, for example...
public class LogToDatabaseTask implements PipelineTask {
public void Run(String xml) {
db.store(xml); // some call to database to store.
}
}
Then a database table containing rules (maybe as XPath expressions), and the class to invoke should those rules be satisfied by the received document. I'd then use reflection - or perhaps a factory(?) - to invoke the correct implementation and run it.
Question
To me, it sounds like there should be some kind of existing pattern to implement something like this which I've missed and can't find online anywhere. Would this kind of approach make sense - or is there some better, perhaps more flexible way of doing this?
As you already mentioned, a rule seems a good fit for this case. You can define a rule that takes facts related to the current state and provide the next action in the sequence. Below is a simple java rule method as example. You can also use a rules framework like drools. The response from the rule can be used with a factory or a strategy:
For example, consider the sequence of actions:
UPDATE_DB
EXTRACT_VALUES
INVOKE_XYZ_SERVICE
END
For every web service request check the rule after every step and execute actions until you receive a rule response with next action END. The rulerequest also contains the contents of input document:
public RuleResponse execute(RuleRequest request) {
//initialization and extraction code here
if(request.previousAction.equals("EXTRACT_VALUES") && ....) {
RuleResponse.nextAction = "INVOKE_XYZ_SERVICE".
}
return response;
}
I know that you tagged the question as Java, but actually you can reuse a lot of the MSDN logical model of the Pipes & filters design pattern. The article is very good and I've used already in Java modules.
First you can also read this about Pipeline_software - it helped me a lot with ideas.
I am using Spring MVC 2.5 and for my model/bean class, at the moment, I use server side validation. One of the validation I wanted to do is check if some of the inputs are not numeric (0-9). The user may input non-numeric characters like "abcd" instead of '1234'.
I have a #Pattern which only accepts positive BigDecimal (it represents dollar amount).
public class OfferSettingBean implements Serializable {
private static final String NUMBER_WITH_DECIMAL_PLACES_ONLY="^\\d+([.]\\d+)?$";
//org.hibernate.validator.pattern
#Pattern(regex = NUMBER_WITH_DECIMAL_PLACES_ONLY, message = "invalid.amount")
private BigDecimal offerSize;
//the rest of the code goes here including setter and getter methods
}
jsp page
<input type="text" name="offerSize" id="offerSize" value="${offerSetting.offerSize}" placeholder="$" />
The problem with my code is, if the user enters a non number character like "asdfsd" it doesnt even reach to the point where it should check the pattern.
Failed to convert property value of type [java.lang.String] to required type [java.math.BigDecimal] for property offerSize; nested exception is java.lang.NumberFormatException
I think the problem is before checking the pattern it binds the string value to BigDecimal which makes it fail.
One ugly solution might be in the offerSize setter method I can check the coming value and do something if it is not a number. But I dont like that one.
What is a better way to deal with such kind of binding problems?
FYI: I know I am going to do client side validation (using JQuery) latter on. Now, I assume the user by passes the client side validation in some way.
The error message is self-explainable.
#Pattern can be used for validation of String arguments. Numbers (int, double, BigDecimal etc) are parsed automatically and do not need special validation.
So, just remove your pattern or make your field String and parse it yourself. (The second solution is bad).
BTW are you sure you indeed need BigDecimal to operate with money? Do you know how double big is? I think that it is big enough to hold total amount of money that have been ever printed in whole world during latest 5 thousand years.
I think the problem is before checking the pattern it binds the string value to BigDecimal which makes it fail.
Yep!
What is a better way to deal with such kind of binding problems?
Not sure what you mean here. There was an error. The error was caught. All seems well. What behavior would you prefer?
FYI: I know I am going to do client side validation (using JQuery) latter on. Now, I assume the user by passes the client side validation in some way.
Even later, one is better off validating both client-side and server-side, IMO. There are many ways client-side validation can fail, both innocent and malicious, and even if that weren't the case, it is nice to be able to reuse server-side code without worrying about all the validation being gone because it was located in client-side Java script.