Can I enable just Spring Session header authentication? - java

For the time being I see no reason to add Redis but all Spring Session examples include it. I want to design with the idea in mind that I might add it later. The thing I want right now is Header Authentication.
How can I enable the Header Authentication without enabling Redis?
(a spring boot single file application as example would be nice)

The MapSessionRepository was created for just that purpose.

This works with version 1.2 and untested, 1.1
#EnableSpringHttpSession
class HttpSessionConfig {
#Bean
MapSessionRepository sessionRepository() {
return new MapSessionRepository();
}
#Bean
HttpSessionStrategy httpSessionStrategy() {
return new HeaderHttpSessionStrategy();
}
}

I think all you need is a filter of type - SessionRepositoryFilter<Session>, which in a Spring Boot application means a #Bean of that type. When you create it you just inject a HeaderHttpSessionStrategy.

Related

is it possible to have Spring configuration relying only on annotations apart from being spring boot application?

I'm new in Spring applications, and see the big difference between configurations in springBoot and spring. So my questin is: apart from spring-boot, is there a way to setup a proper spring application(with web mvc, security, aop, ...), without any xml config file (ie : config relying only on annotations).
Yes, there is a way to do this in Spring. Spring Boot is after all an enhanced, autoconfigured Spring (with other cool features). That means that everything there is in Spring Boot should be achievable in Spring as well, but you would have do a bit/a lot of Your own extra work.
Moving straight to the point, in order to achieve what you want, you would need to undertake the following steps:
Create a class, which will store all the configuration (basically the properties you would store in the xml file) - let's call it AppConfig.class
Annotate the AppConfig.class with #Configuration - this will inform Spring that this class is the source of configuration;
Annotate the AppConfig.class with #ComponentScan("com.app") - here, You need to provide a package, from which Spring has to start component scanning in order to find Beans to be registered in Spring Container. Important note is, that it will scan the package and it's subpackages, so you would mostly want to provide here the top level package;
If you need some data to be injected into your beans, you would want to use the #PropertySource("classpath:application.properties") - I have provided here the default value, which Spring Boot uses internally in case you want to inject some data into your beans at runtime. For this to work, you need to inject into AppConfig.class an Environment.class
To show it on the example:
#Configuration
#ComponentScan("com.app")
#PropertySource("classpath:application.properties")
public class AppConfig {
// it will help to pull the properties incorporated in the file you have provided in the #PropertySource annotation
private Environment environment;
//inject it
public AppConfig(Environment environment) {
this.environment = environment;
}
// build your beans - the getProperty method accepts the key from application.properties
// file and return a value as a String. You can provide additional arguments to convert
//the value and a default value if the property is not found
#Bean
public Product product() {
return new Product(
environment.getProperty("product.name", "XXX"),
environment.getProperty("product.price", BigDecimal.class, BigDecimal.ZERO),
environment.getProperty("product.quantity", Integer.class, 10)
);
}
}
I hope that it helps

How to Configure Spring Oauth2 for Multi tenant

I'm currently developing multi-tenant application using spring and using oauth. Every tenant will have different database. If my url is tenant1.xxx.com, then it will use tenant1 database, etc.
My request already successfully routed using AbstractRoutingDataSource but not the authentication. So when I ask an access token, it still using the default datasource. I think my problem is in oauth2 configuration that set datasource like TokenStore, etc.
#Autowired
private DataSource dataSource;
#Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
Is there anyway that token store can choose datasource according to current tenant?
Let me try to give solutions
1) If you check to code inside the JdbcTokenStore then we will find that it's using inside the JdbcTempaltes so JPA or Hibernate routing will not work for that in that case a part of the solution you have to implements org.springframework.security.oauth2.provider.token.TokenStore with JPA implementation.
2) If you do not like to do a solution No 1 then you can also implement AbstractRoutingDataSource and while creating TokenStore passed the routing data source.

Using OpenSessionInViewInterceptor in Java Config not WebXML

I have seen a lot of examples of adding OpenSessionInViewFilter and OpenSessionInViewInterceptor, and it seems like the Interceptor is the way I need to go. My application is setup using Java Configuration and not web.xml style configs.
In my WebMvcConfigurerAdapter I am setting up the Interceptor as such:
#Bean
public OpenSessionInViewInterceptor openSessionInViewInterceptor(){
OpenSessionInViewInterceptor openSessionInViewInterceptor = new OpenSessionInViewInterceptor();
openSessionInViewInterceptor.setSessionFactory(sessionFactory);
return openSessionInViewInterceptor;
}
This seems to be fine, but the problem is how do I get this hooked into my Spring configuration?
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addWebRequestInterceptor(openSessionInViewInterceptor());
super.addInterceptors(registry);
}
After trying this it compiles and runs just fine, but I still run into could not initialize proxy - no Session errors on the front end. Is it actually hooking up like I want through this function, or is there another (more correct) way to add this interceptor?
Has anyone configured this kind of OpenSessionInViewInterceptor inside Java Spring config? Thanks in advance.

Enable schemaCreationSupport in spring-boot-starter-data-solr

I use spring-boot-starter-data-solr and would like to make use of the schmea cration support of Spring Data Solr, as stated in the documentation:
Automatic schema population will inspect your domain types whenever the applications context is refreshed and populate new fields to your index based on the properties configuration. This requires solr to run in Schemaless Mode.
However, I am not able to achieve this. As far as I can see, the Spring Boot starter does not enable the schemaCreationSupport flag on the #EnableSolrRepositories annotation. So what I tried is the following:
#SpringBootApplication
#EnableSolrRepositories(schemaCreationSupport = true)
public class MyApplication {
#Bean
public SolrOperations solrTemplate(SolrClient solr) {
return new SolrTemplate(solr);
}
}
But looking in Wireshark I cannot see any calls to the Solr Schema API when saving new entities through the repository.
Is this intended to work, or what am I missing? I am using Solr 6.2.0 with Spring Boot 1.4.1.
I've run into the same problem. After some debugging, I've found the root cause why the schema creation (or update) is not happening at all:
By using the #EnableSolrRepositories annotation, an Spring extension will add a factory-bean to the context that creates the SolrTemplate that is used in the repositories. This template initialises a SolrPersistentEntitySchemaCreator, which should do the creation/update.
public void afterPropertiesSet() {
if (this.mappingContext == null) {
this.mappingContext = new SimpleSolrMappingContext(
new SolrPersistentEntitySchemaCreator(this.solrClientFactory)
.enable(this.schemaCreationFeatures));
}
// ...
}
Problem is that the flag schemaCreationFeatures (which enables the creator) is set after the factory calls the afterPropertiesSet(), so it's impossible for the creator to do it's work.
I'll create an issue in the spring-data-solr issue tracker. Don't see any workaround right now, other either having a custom fork/build of spring-data or extend a bunch of spring-classes and trying to get the flag set before by using (but doubt of this can be done).

How do I configure Sniffy with Spring Boot?

Sniffy is a cool little project:
Sniffy counts the number of executed SQL queries and provides an API for validating them It is designed for unit tests and allows you to test if particular method doesn't make more than N SQL queries Especially it's useful to catch the ORM N+1 problem at early stages
It also provides a servlet filter which injects HTML into a page with a popup showing you executed queries. The documentation explains how to configure it for a traditional web.xml based application but not Spring Boot. I managed to register the servlet filter by adding this bean to an #Configuration class:
#Bean
public FilterRegistrationBean snifferFilter()
{
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
SnifferFilter filter = new SnifferFilter();
filter.setInjectHtml(true);
filterRegistrationBean.setFilter(filter);
filterRegistrationBean.setName("sniffer");
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
I also updated the JDBC url, the documentation says:
add sniffer: prefix to the JDBC connection url For example jdbc:h2:~/test should be changed to sniffer:jdbc:h2:mem:
So I added the following to my application.yml:
spring.datasource.url: sniffer:jdbc:mysql://localhost:3306
But when I start my application it fails with this error:
URL must start with 'jdbc'
Sniffy author here!
Indeed as of version 3.0.7 (April 2016) you have to specify the driver class name explicitly in your Spring Boot application. There's an open issue in a bug tracker to configure it automatically.
By the way sniffy 3.0.5 introduced an out-of-the box support of Spring Boot using #EnableSniffy annotation, so you do not have to create the FilterRegistrationBean yourself anymore - just put the annotation to your application class like this:
import io.sniffy.boot.EnableSniffy;
#SpringBootApplication
#EnableAutoConfiguration
#EnableSniffy
public class Application {
public static void main(String[] args) throws ClassNotFoundException {
SpringApplication.run(Application.class, args);
}
}
I managed to figure out the problem, Spring Boot makes extensive use of auto configuration and was trying to detect the DatabaseDriver from the connection string. As the connection string no longer starts with jdbc it was encountering a problem.
It was simply a case of specifying the driver-class-name in my application.yml rather than letting Spring Boot trying to auto detect it:
spring.datasource.driver-class-name: io.sniffy.MockDriver

Categories

Resources