Wiring in spring-session without using AbstractHttpSessionApplicationInitializer or web.xml? - spring

So I have an existing internal application framework which only requires consuming applications to register a single filter in their web.xml - a DelegatingFilterProxy which references a CompositeFilter. As part of that CompositeFilter we have a whole slew of other filters in a specific order (some custom, springSecurityFilterChain, etc).
I now want to bring spring-session into the mix but I don't want to use the WebApplicationInitializer (I need to support servlet 2.5 containers) nor do I want to have to have every application modify their web.xml. I'd want to provide it as part of our internal framework and simply throw the springSessionRepositoryFilter into our CompositeFilter. Seems simple enough - but it seems that no matter which position I put it in (we currently have 11 or so other filters in there) things just don't seem to work. Our authentication seems to break and things just don't work. All does work fine if I do manually add the springSessionRepositoryFilter directly to web.xml - so I'm confused. Any help?

I figured it out. The SessionRepositoryFilter has to come before the RequestContextFilter in the filter chain. Also have to make sure to turn off disable url rewriting in Spring security, since the springSecurityFilterChain will come after the SessionRepositoryFilter. If you don't then the re-writing of the URLs with the _s parameter won't work.

Related

In Spring Boot how do you register custom converters that are available when parsing application configuration?

In a Spring Boot application how do you register custom converts to be used when processing application configuration?
I have made a custom convert (org.springframework.core.convert.converter.Converter) so it can be used by the ApplicationConversionService/Binder to parse #ConfiguraitonProperties defined in application.properties and application.yaml configuration files but do not know how to register it.
I have tried the solution here https://stackoverflow.com/a/41205653/45708 but it creates an instance of my converter after the application configuration parameters have been processed.
I ran into this issue myself recently. From what I can tell, the key issue is that binding to configuration properties occurs very early in the Spring startup process, before the Application Context is fully initialized. Therefore the usual methods for registering a converter are not reliable. In fact the ConversionService used for configuration binding appear to be a one-off and not really connected to the ConversionService that is stored in the Application Context.
I was able to get something working but it feels like a hack, as it relies on internal implementation details that may work today but not tomorrow. In any case, this is the code I used:
((ApplicationConversionService) ApplicationConversionService.getSharedInstance()).addConverter(myCustomConverter);
The trick I found was to make sure this gets called as soon as possible at application startup so that it gets called before the configuration binding where it's needed. I put it in a #PostConstruct block inside my main #SpringBootApplication class as this seemed to get invoked early on, at least in my case.

spring boot: separate REST from static content

I'm using spring-boot-starter-data-rest and spring-boot-starter-web.
I've made a simple project using a CrudRepository, letting spring boot generate the rest request mappings.
Now, I want to add a client -- making the rest calls -- live under ./.
Hence, I'm trying to prefix the paths for the rest calls (and only those!) with /api.
I've tried the answers from :
How to specify prefix for all controllers in Spring Boot?
using settings in the application.properties file
server.contextPath=/api/*
spring.data.rest.basePath=/api/*.
But still the static content (e.g. index.html, *.js, *.css) is not fetched using ./. There urls are also prefixed by "/api/".
The rest calls are properly served under /api/foos.
Is there a way to tell spring not to treat urls that lead to sources located in src/main/resources/public as 'rest-controllers'?
Update
Setting the property
spring.data.rest.basePath=/api/*
works perfectly. (I still had a programmatic bean configuration in my sandbox overriding this setting).
Spring controllers are made for serving both HTML and JSON/XML. The first one is done via Spring MVC Views and some template engine like Thymeleaf, the latter is handled entirely by Spring and #RestController.
There's no way to have a context path for only the controllers that returns JSON or XML data, and not for the other controllers as well, this also goes for static content. What you typically do is have some static variable containing the prefix you want for your APIs, and the use that in the controller's #RequestMapping. i.e.
#RestController
#RequestMapping(MyConstants.API_LATEST + "/bookings")
public class MyBookingsController {
...
}
You probably want to approach the prefix problem with something along these lines anyway. It is common to have to support older API versions when you have breaking changes, at least for some time.

Spring Security 4 sessionRegistry doesn't populate Principal list

I am trying to implement a function where a admin user can terminate another user's session. I followed the official Spring Security documentation here: http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#list-authenticated-principals and started with getting all currently logged in users through sessionRegistry.getAllPrincipals(), but it always returned an empty list.
I set a breakpoint in SessionRegistryImpl.registerNewSession() and could see it did indeed get invoked and it did add the UserDetails (my own implementation with both equals() and hashCode() implemented) to the hashmap principals. But when I access sessionRegistry bean from a Spring MVC controller, the list is always empty.
My configuration looks pretty much the same as the documentation.
How to fix this? Did anyone successfully get SessionRegistry to work with Spring Security 4? I remember I made it work with Spring Security 3 by following these intructions(enter link description here)
OK, so I fixed the issue by cleaning up the Spring configuration files, as suggested by the comments. Someone messed up with the web.xml - he added a reference to the context XML that is already referenced by the Spring's DispatcherServlet, causing it to be loaded twice. He didn't know it, because Spring references the file implicitly.
P.S.
I learned my lessons, but 2 things the Spring folks could do better (maybe in Spring 5?):
There shouldn't be implicit context file loading. Currently, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application's WebContent/WEB-INF directory. Convention over configuration fails in this case.
There should be warning when a bean is loaded twice, if someone need to override a bean definition, he must declare explicitly. Otherwise it would take a lot of time to debug the kind of error this mistake will cause.

Spring security - implement oauth with existing FilterChainProxy

we have existing web application built with Spring security 3.1 ,Wink(for rest)
we now need to add oauth2 (client_credentials flow) for several resources, i looked into many examples and all of them using the Http namespace configuration along with spring dispatcher servlet (which we didn't have till now)
problem is that http namespace is creating a springSecurityFilterChain which we already had in the application , so first thing i renamed the existing filter so the default could co-exist with the old one.
but this does not work, its either the existing chain working for requests or the new one.
i have tried the following already
1. disabled dispatcher servlet context by giving empty config location (in web.xml)
2. tried to have the oauth configuration in application-context.xml (right to the existing FilterChainProxy)
3. Allow the /oauth/token in existing chain by setting its filter to none (so the new can take over)
4. tried to declare the oauth filters in the existing chain but there was a problem with its not getting the right clientAuthentication
i really don't know what else to try - so the question is : is it possible to have both declared in the same webapp ? or is it possible to declare oauth2 configuration in the old fashion.
thanks
Shlomi
I managed to do that eventually, having the API (protected with oauth) completey separated url from the rest of the application.
so the Http namespace is creating the springSecurityFilterChain bean and the others just have different bean names. everyone is delegated through the DelegatingProxy in web.xml
i needed to puth the API URL prefix in other chains and allow all requests through , leaving the oauth security chanin to deal with security.
(i.e filter-chain pattern="/api/**" filters="none)
regarding the spring oauth2 bounded to spring MVC so tight i think is not a good implementation.
the mapping of the dispatcher servlet cannot be for /* but have to be something like /auth/*
so a special filter inherit from ClientCredentialsTokenEndpointFilter with special path like super("/auth/oauth/token") was needed.
it also cannot be /api/* since this is the real API URI mapped by our rest framework (wink RestServlet)
so we have something like this
http://server:port/context/auth/oauth/token
http://server:port/context/api/someresource (protected with oauth2)
http://server:port/context/rest/someresource (old rest for application)
Shlomi

Spring overwriting controller

I provide a highly customisable application to my clients which is working totally by itself. But If one my client wants to overwrite any Controller, I want to replace my implementation by theirs. However just overwriting the controller causes an ambiguous definition of mappings.
I have been using Component Scanning to load beans.
The potential solutions came to my mind are:
Using component scanner with excluding by a custom filter? (This seems not so easy)
Using a xxxxPostProcessor to remove some beans? (How?)
Any help?
If I got your Question properly,
You can differ implementation by changing URL to particular Implementation name
Say Telecom is interface and AirtelImpl and RelianceImpl are Controllers then
Your request mapping
#RequestMapping(value= "/airtel/doBilling")
#RequestMapping(value= "/reliance/doBilling")
In this way, Implementation flow will differ.
I have followed these steps:
Created a custom annotation: #Devoted
Created a custom ImportBeanDefinitionRegistrar. Iterated already registered bean definitions to find out `#Devoted #Controller's and removed them.
Based on a request I will provide implementation details.

Resources