Spring boot/CRNK Custom Query Spec URL Mapping For Single Endpoint - spring

I'm currently trying to change the functionality of the QuerySpecUrlMapper for only one specific endpoint. In particular, we want to disable the behavior that splits a string parameter by commas. I've figured out I can do this by getting the default URL mapper and calling setAllowCommaSeparatedValue, but I'm not sure how to do this for the specific endpoint I want. We're using Spring, and I tried Autowiring CrnkBoot into my Repository object so I could get the UrlMapper that way, but this breaks the whole thing in strange ways I don't yet understand. Some exception about "Cipher not initialized"
Anyone have ideas about how to handle this?

Related

How to find the REST method that matches a request URI in Spring Boot within an interceptor?

To give you a background, we have an application with lots of REST services. Now for these services there are security permission entries. Now we could have an AccessVoter that intercepts all the request to check whether the user has permission to a resource but this is inefficient as we have to load thousands of rows from database and check the incoming request with the pattern saved in database. The pattern that I mentioned is exactly the same as the pattern that the developer put in their REST method, for example:
#PostMapping(value = "/accounts/{id}/advisers/{adviserId}")
Or
#PostMapping(value = "/accounts/{id}/advisers/address/{adrId}")
You can see how complex it can be and going through the records to find a match is expensive while Spring has already done the mapping and it can find the associated method very nicely.
We could create an aspect to check the permissions before the method invocation but at that time is too late as there are validation layers that happens before
I was thinking if we could have an access voter and then ask Spring to give us the method that it's going to invoke so that we can read the annotation, in above example #PostMapping and then find the pattern (say e.g. /accounts/{id}/advisers/{adviserId}) so we can only query that pattern from database, then this will be very efficient and less complex in our code.
The question is whether it's possible to get this information from Spring Boot or not?
Is there any other way than using Spring's AccessVoter to do the job? For example when we configure ResourceServerConfigurationAdaptor we have this code:
http.authorizeRequests()
.antMatchers(oAuth2AuthenticationSettings.getProtectedUrlPattern().split(","))
.authenticated().accessDecisionManager(accessDecisionManager);
As you can see accessDecisionManager is the one that returns AccessVoter but we could also set .authenticated().expressionHandler(...) which I don't know what it is used for. Can it be used for our purposes?
We don't want to use #PreAuthorize as it means we have to go and annotate all of our REST services.

Validate a HTTP-Header field in a Spring RestController

I'm looking for a way to validate whether the custom header 'X-Client-Id' is set to a value defined in a Repository within an HTTP request sent to a REST-controller in SpringBoot.
I see tutorials (like this) which includes the header in the method like this: #RequestHeader(value="User-Agent"). I assume I would have to write that line to every method and inject a common validator-bean to verify the value.
Another stackoverflow answer seems to suggest using an HandlerInterceptor. I'm not sure though if that's applicable to header values and REST endpoints.
So what is the recommended way to validate all methods of a class/REST-controller whether a specific header is set or not?
Basically the easiest (and most logical) way is to catch the Request before it gets to your Controller. That can be achieved either with a HandlerInterceptor as the other answer states or with a simple Filter like OncePerRequestFilter.
Extend that class, override the doFilterInternal() method as doFilter() is final, extract the proper header value, check it against whatever you need and depending on the value, either throw an Exception or continue with the chain.

Can i access request parameter in jackson BeanSerializerModifier?

I am using Jersey to implement rest api and Jackson to provide JSON support. I am trying to remove certain properties before serialization by overriding BeanSerializerModifier.changeProperties method.
But removing properties will be based on query parameter. Is there any way to access the query parameter in my implementation?
Use of BeanSerializerModifier itself would get complicated as the method is only called once when construction necessarily JsonSerializer for the first time. As to passing query parameters, you could pass them using contextual attributes and ObjectWriter (constructed from ObjectMapper), but that means taking over quite a bit of serialization automation from Jersey.
There is one mechanism that could be helpful in modifying serialization aspects without taking over the whole process: registering ObjectWriterModifier, using ObjectWriterInjector. These are part of Jackson JAX-RS provider, added in Jackson 2.3. Without knowing more details I don't know how easy this would be; part of the issue is that query parameters are more of an input side things, so there is no direct access to them from output processing side.

Best practice for validating a URL with Spring-MVC?

I am using Spring MVC for my web application.
I need to validate that the URL the user inputs is valid and was wondering if there is something in Spring that can do the basic checks for me (for example starts with http/https, has domain name etc).
ValidationUtils only contains very basic checks and I know I can write a regular expression in the validate() method however prefer to avoid it inm case someone has already done it :)
Thanks
In the past, I have always utilized Hibernate Validator. Simply annotate the appropriate field in your form bean with a #URL constraint.
If you've never used the ORM part of Hibernate before, don't let that scare you. The Validator portion is not dependent on the ORM stuff, and integrating it into Spring is very straightforward.
If for some reason you can't use Hibernate Validator... or you just want to stick with what you're comfortable with, a good place for regex's is RegExLib.com; several patterns that can match a URI are listed there.
Ended up using UrlValidator from apache commons.
I know this question is quite old, but I just need the same and I think I'll go with the PropertyEditors in SpringFramework.
More precisely there is URLEditor, which you can use to convert a String representation to an actual URL object.
Here is a link to the respective documentation:
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-beans-conversion
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/propertyeditors/URLEditor.html
In my case, I think about using the following code within a Spring Validator to check whether a String entered by a user is a valid URL or not:
try {
PropertyEditor urlEditor = new URLEditor();
urlEditor.setAsText(field.getValue());
} catch (IllegalArgumentException ex) {
errors.rejectValue("nameOfTheFieldToBeValidated", "url_is_invalid");
}
However, as for now, I'm unsure whether it is possible to configure which protocol is going to be accepted as valid (i.e. URLEditor seems to also accept URLs starting with "classpath:")
Use a spring interceptor:
http://java.dzone.com/articles/using-spring-interceptors-your

Spring 3.0 URL pattern validation

I'm wanting to to add an endpoint like /user/foo where foo is one of a set of values determined at runtime. I'm wondering what the best way is to do this in Spring, or indeed if it should even been done in Spring an not handled at the controller level.
I'm currently using Springs security filter chain, so I did think about putting a filter in front of /user/* to do this validation. Is this a reasonable solution or is there a more desirable solution I have missed?
You can use #PathVariable annotation on a method argument. #PathVariable also allows regex if you need to validate the structure of the varible.
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping
http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/PathVariable.html
and for the regex
http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html

Resources