Spring MVC Allow header - spring

I assume that Spring Dispatcher automatically include Allow header when a particular URL is requested via OPTIONS method. Is there any way we can override the Allow header which Spring sets Out of box? If yes, what would be the best way?

I meant to say Dispatcher servlet.
FYI. Answer to this question is HttpServlet's doOptions method identifies the methods supported by DispatcherServlet and sets the OPTIONS header. So what we can do is to add a filter to explicitly override the OPTIONS header

Related

Does Spring Boot Support Multiple Content Negotiation Strategies Base On URL Pattern

Our Spring Boot webapp consists of a couple of URL strategies. The /api URL's are for REST services and content negotiation is consistent with best practices (headers or request parameters). The /web URLS are for a legacy Freemarker application which uses URL extensions for mapping content type (.html, .json, etc). A recent change by Spring has caused the problem (https://github.com/spring-projects/spring-framework/issues/24179).
The content negotiation for the two URL's are different and I was wondering if we could define multiple content negotiation strategies...using URL's to select between them.
Yes, content negotiation is possible in the Spring Boot application as you can use Request parameter or header values to return different content-type based on your requirement for example. You can use the same URL pattern and use content-type request parameter to get the desired type and return the content like .html or.json but make sure you are adding marking as #RequestMapping(value = "sign_in", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_HTML_VALUE})

How to override InvalidSessionStrategy in Spring Security

The default implementation of InvalidSessionStrategy i.e. SimpleRedirectInvalidSessionStrategy in Spring security redirects the request to a default url. This default url comes from a final variable.
I would like to override the behavior by not redirecting all the time to the same url. How could I achieve that ? If I create a custom implementation of InvalidSessionStrategy, how can I use that ?
This is my configuration right now
and()
.addFilterAfter(mySpringSecurityConfig.forceLogoutFilter(), PreAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.invalidSessionUrl("http://xxx/login.jsp")
.sessionAuthenticationErrorUrl(PropertyMgr.getCarnivalURL("http://xxx/login.jsp"))
But I don't want to use "http://xxx/login.jsp" for all invalid sessions. Thanks for the help.
Please post your entire configuration and the Spring Security version, so that we can have the whole picture.
However, to override InvalidSessionStrategy, simply define your class implementing this interface.
Then find a way to put your implementation into SessionManagementFilter.
One way can be via SessionManagementConfigurer.
In the worst case you can always extend SessionManagementFilter, put your InvalidSessionStrategy there, and substitute the default sesssion filter.

Securing and permitting access to spring rest controller with ant matcher and method level security side-by-side?

First of all my application is build with spring boot and security.
So I have several rest controllers (resources). One controller provides multiple methods to get/post different kind of data. But I have cases where some methods should be public and others needs authentication.
For example:
GET /api/object/method1 <-- Needs authentication
GET /api/object/method2 <-- Public
POST /api/object/method3 <-- Needs authentication
POST /api/object/method4 <-- Public
What is best practice to secure this resource? I can't secure url with antMatcher with following pattern /api/object/**. Because then the public methods would be secured as well. Also I can't secure by request type (GET, POST).
One option I thought about was using only method level security (eg #Secured etc). This would mean that I need to annotate a lot of methods.
Another thought that comes to mind is dividing resource to 2 parts.
For example creating
ObjectResource.java
ObjectResourcePublic.java
One controller base URL would be /api/public/ and second simply /api/
Then I could use antMatcher for these URLS.
Is my only option to secure every path separtely or every method separetly?
What other options do I have to do this kind of partial securing one resource?
You may use below methods apart from above mentioned methods.
1. Write Interceptor/filter
2. Use Aspect and define advise

For validating session attribute, which is better in spring - Interceptor or Spring AOP?

In my application, after a user is logged in, every time he sends a request (get/post), before calling the method in controller, i want to verify the session attribute set in the request (i set a session attribute during his login). I see that this can be implemented through spring interceptors (OR) spring AOP. which one should i use?. I have a feeling interceptors are outdated. Or is there a way in spring security which does this for me?
So you want this intercept to happen only for all the controller methods ..? Does the controller have Base URL that its getting invoked for (post/get/delete)...? Is it more like you want to intercept the http request for a particualt URL ..? like this one
<intercept-url pattern="/styles/**" filters=" .." />
If your use case is boiled down to a particular URL pattern then you can write a custom filter extending GenericFilterBean and you can plug it to the filters attribute.So this will get called for every request matching url pattern and in your custom filter you can do whatever you wanted to do.
What if you try implementing a simple Filter? You can extend already existing Spring filter, or create your own by implementing javax.servlet.Filter
The spring security way seems the best way to me with access to specific roles also can be assigned. very good example given in http://www.mkyong.com/spring-security/spring-security-form-login-using-database/

Spring HandlerInterceptor vs Servlet Filters

HandlerInterceptors in Spring can now be configured to be invoked only on certain URLs using <mvc:interceptors>.
Servlet Filters can achieve same functionality (logging, security etc). So which one should be used?
I think with Interceptors, one can use ModelAndView object to work with Models so it has more advantages. Can anyone draw out scenarios where Filters or Interceptors have advantages over the other?
The org.springframework.web.servlet.HanderInterceptor Interface JavaDoc itself has a two paragraphs that discuss this question:
HandlerInterceptor is basically similar to a Servlet 2.3 Filter, but
in contrast to the latter it just allows custom pre-processing with
the option of prohibiting the execution of the handler itself, and
custom post-processing. Filters are more powerful, for example they
allow for exchanging the request and response objects that are handed
down the chain. Note that a filter gets configured in web.xml, a
HandlerInterceptor in the application context.
As a basic guideline, fine-grained handler-related preprocessing tasks
are candidates for HandlerInterceptor implementations, especially
factored-out common handler code and authorization checks. On the
other hand, a Filter is well-suited for request content and view
content handling, like multipart forms and GZIP compression. This
typically shows when one needs to map the filter to certain content
types (e.g. images), or to all requests.
Spring Handler interceptors allow you to hook into more parts of the request lifecycle, and get access to more information in the process. They're often more intimately coupled to the request/response cycle than filters.
Filters are more suitable when treating your request/response as a black box system. They'll work regardless of how the servlet is implemented.
If you're using Spring MVC, there's little reason to write new logic as a servlet filter. Everything filters can do, interceptors can do more easily and more elegantly.
Remember also, servlet filters have been around for much longer than interceptors.
With a Spring interceptor, you have access to the Handler which may be useful. Also, with a Spring interceptor, you have access to execute logic before the view renders and after the view is rendered.
Servlet Filter:
A filter as the name suggests is a Java class executed by the servlet container for each incoming http request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.
This behaviour allow to implement common functionality reused in many different contexts.
As shown in the figure above, the filter runs in the web container so its definition will also be contained in the web.xml file.
The filter include three main methods:
init: Executed to initialize filter using init-param element in
filter definition.
doFilter: Executed for all HTTP incoming request that satisfy
"url-pattern".
destroy: Release resources used by the filter.
Interceptor:
Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sofisticated behaviour because can access to all Spring context.
The Spring interceptor are execute in SpringMVC context so they have be defined in rest-servlet.xml file:
The interceptor include three main methods:
preHandle: Executed before the execution of the target resource.
afterCompletion: Executed after the execution of the target resource
(after rendering the view).
postHandle: Intercept the execution of a handler.

Resources