Generate two different SP metadata using Spring Security SAML´ - spring-saml

We need to configure two different IdPs. So far so good, but the problem is that we need to configure forceAuthN for one of the IdPs. Another thing is that one IdP is using HTTP-Artifact for bindingsSSO, while the other is using HTTP-POST. Therefore it seems that we need two different SP metadata.
What is the best approach? I guess it's not a problem if we write the metadata ourselves, but we want Spring Security SAML to generate these.
We tried to configure two different metadataGeneratorFilters by extending the MetadataGeneratorFilter class. The problem now is that only metadata for one of the SPs are built, and the reason is simply the following line in the processMetadataInitialization method:
if (manager.getHostedSPName() == null) { ...
The MetadataManager class can, as far as I know, only hold one hostedSPName, not two.

You don't need separate metadata in order to control selection of bindings or forceAuthN. These settings are configured in the AuthnRequest sent to IDP. Just make sure that your SP metadata contains both HTTP-Artifact and HTTP-POST endpoints (which it does by default).
The AuthnRequest settings are configured using instances of WebSSOProfileOptions. Extend class SAMLEntryPoint, override method getProfileOptions and return correctly configured WebSSOProfileOptions depending on the IDP you are connecting to and the requirements you have. Details are in the manual.
The forceAuthN in AuthnRequest is configured using property forceAuthn. You can select which binding (artifacts vs. post) should IDP use to deliver the SAML message back to SP with property assertionConsumerIndex.
You cannot use automatic MetadataGenerator for generating of two different sets of metadata in one instance. In order to do so you can use pre-configured metadata - but I don't think it's needed in your case.

Related

Spring boot jpa entity table name from property file

We are working on a spring boot library to generate and validate OTP. It uses database to store the OTP.
We are using Spring Data JPA for Database operations, as it will be easy to handle multiple database systems according to the project.
Now we have ran in to a problem, most of our projects uses Oracle with a single database.
When using the the same lib in multiple projects there is a name conflict.
So we want the name of the OTP table to be configurable using a property file.
We tried #Table(name = "${otp-table-name}") But its not working.
We did a lots of research and found out the hibernate naming strategy configuration can help.
But we dont want to use lots of configuration in our library as we need the library to be easily usable in the projects.
Can someone help us on this aspect.
Thanks in advance.
You can dynamically determine the actual DataSource based on the current context, use Spring's AbstractRoutingDataSource class. You could write your own version of this class and configure it to use a different data source based on the property file.
This allows you to switch between databases or schema without having to change the code in your library.
See: https://www.baeldung.com/spring-abstract-routing-data-source
Using a NamingStrategy is good approach.
You could let it delegate to an existing NamingStrategy and add a prefix.
Use a library specific default for the prefix, but also allow users of your library specify an alternative prefix.
This way your library can be used without extra configuration, but can also handle the case of multiple applications using it in the same database schema.
Of course this might involve the risk of someone using the default prefix without realizing that, that is already used.
It is not clear what the consequences of that scenario are.
If the consequences are really bad you should drop the default value and require that a project specific prefix is used.
When no prefix is specified throw an exception with an instructional error message telling the user, i.e. the developer how to pick a prefix and where to put it.

Spring Boot: Handle configuration in multitenant application

I am implementing a Spring Boot application which will be providing a multitenant environment. That is achieved in my case by using a database schema for each customer. Example see this project.
Now I am wondering how to implement tenant-specific configurations. I am using #ConfigurationProperties to bundle my property values, but these are getting instantiated once and not for each tenant.
What if I would like to use Spring Cloud Config with multiple tenant specific git repository as an configuration backend. Would it be possible when using a jdbc backend for Spring Cloud Config?
Is there any way with default Spring mechanisms or do I have to implement a database based configuration framework myself?
Edit: For example I have two tenants called Tenant1 and Tenant2. Both are running over the same application in the same context and are writing in the database schemes tenant_1 and tenant_2.
Identification of tenants is happening over keycloak (see Spring Keycloak multi tenant example). So I identify the tenantId from the jwt token and select the database connection like described here.
But now I would need the same mechanism for #Configuration beans. Since #Configuration beans are as far as I know Singletons, so there is always ONE configuration per application scope, and not ONE configuration per tenant.
So using Spring Cloud Config Tenant1 is using https://git-url/tenant1, Tenant2 is using Hashicorp Vault as backend and perhaps Tenant3 will be using a jdbc based configuration backend. And all of that in ONE (of course scalable) application.
In case your application uses tenant specific files (html templates etc), the following can be applied. As I have used the below approach for handling many tenants and works fine and easy to maintain.
I would suggest that you maintain a consistent configuration source (JDBC) for all of your tenant configurations. This helps you have a single source that is cacheable and scalable for your application. Also, you could have your tenants navigate to a configuration page to manage their settings and alter them to suit their needs at any point of time on the fly. (Example Settings: Records Per Page, Theme, Logo, Filters etc...)
Having the tenant configuration in files in git will be a difficult task when you wanted to auto-provision tenant's when they sign-up as it will involve couple of distributed services. Having them in a TenantSettings table with the tenantId as a column could help you get the data in no time and will be easy.
You can use Spring Cloud Config for your scenario and it is adoptable. It is easily configurable and provides out of the box features. For your specific scenario, you can have any number of microservices running yet all controlled by one Spring Cloud Config Server which is connected to one Git Repository. Your all microservices are asking configuration properties from Spring Cloud Config Server and it is directly fetching properties from Git Repository. That repository can have multiple property files. It can hold common properties for all the microservices or specific service based configuration properties. If you want to keep confidential properties more securely, that is also made possible via HashiCorp vault. I will leave an image below for you to get a better idea about this concept.
In the below image, you can see the Git Repository with common configuration property files and specific configuration property files for different services yet in same repository.
I will add another image for you to get a better idea how does this can be arranged with application profiles as well.
Finally I will add something additional to show the power of Spring Cloud Config and out of the box features it allows us to play with. You can automatically refresh configuration properties in running application as well. You can configure Spring Cloud Config to do that. I will add an architectural diagram to achieve that.
References for this answer is taken from Spring in Action, Fifth Edition
Craig Walls

WSO2 Identity Server - Custom JDBC User Store Manager - JDBC Pools

WSO2 Identity Server 5.0.0 (and some patches ;))
It does not appear that custom JDBC user store managers (child of JDBCUserStoreManager) use a JDBC pool. I'm noticing that I can end up session closed errors and sql exceptions whereas the Identity Server itself is still operating OK with its separate database connection (a configured pool).
So I guess I have two questions about this:
Somewhere up the chain, is there a JDBC pool for the JDBCUserStoreManager? If so, are there means to configure that guy more robustly?
Can I create another JDBC datasource in master-datasources.xml which my custom JDBC user store manage could reference?
Instead of using your own datasources/connections, you can import Carbon Datasources and use those (they come with inbuilt pooling and no need to worry about any configurations etc). You can either access these programmatically by directly calling ndatasource component or access them via JNDI.
To access them directly from ndatasource component:
The dependency:
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
<version>add_correct_version_here</version>
</dependency>
(You can check repository/components/plugins to find out the correct version for above dependency)
You can inject DataSourceService as in this code (the #scr.reference tag refers to the service you need to inject, this uses maven scr plugin to parse these dependencies when building the bundle).
Note that when you follow this approach you'll have to build the jar as an OSGi bundle as it uses declarative services (and have to place it in repository/components/dropins). Otherwise the dependencies won't be injected at runtime.
Next, you can access all the data sources as:
List<CarbonDataSource> dataSources = dataSourceService.getAllDataSources();
Rajeev's answer was really insightful and helped with investigating and evaluating what I should do. But, I didn't end up using that route. :)
I ended up looking through the Identity Server and Carbon source code and found out that the JDBCUserStoreManager does end up creating a JDBC pool configured by the properties you set for that manager. I had a class called CustomUserStoreConstants for my custom user store manager which had setMandatoryProperty called by default to set:
JDBCRealmConstants.DRIVER_NAME
JDBCRealmConstants.URL
JDBCRealmConstants.USER_NAME
JDBCRealmConstants.PASSWORD
So the pool was configured with these values, BUT that was it...nothing else. So no wonder it wasn't surviving the night!
It turned out that the code setting this up, if it found a value for the JDBCRealmConstants.DATASOURCE in the config params, it would just load up that datasource and ignore any other params set. Seeing that, I got rid of those 4 params listed above and forced my custom user store to only allow having a DATASOURCE and I set it in code with the default JNDI name that I would name that datasource always. With that, I was able to configure my JDBC pool for this datasource with all params such as testOnBorrow, validationQuery, validationInterval, etc in master-datasources.xml. Now the only thing that would ever need to change is the datasource's configuration in that file.
The other reason I went with the datasource in the master-datasources.xml is that I didn't have to decided in my custom user store's code which parameters I would want to have or not have and just manage it all in the xml file easily. This really has advantages with portability of configs and IT involvement for deployments and debugging. I already have other datasources in this file for the IS deployment.
All said, my user store is now living through the night and weekends. :)

Full integration of encrypted properties in Spring 4/Boot

We're using Jasypt to encrypt some config properties (database passwords) but since the decryption key is stored on each environment's file system we have to do some manual #Bean configuration to load the password from the file then overlay loading properties with an EncryptablePropertiesPropertySource.
Because it is so manual we've had to run this code in #PostConstruct of the WebApplicationConfig class and (although this hasn't happened yet) it runs the risk of loading these after the datasource bean is configured with calls to the Environment - giving null pointer exception. #Lazy loading would be an option but obviously this means we'd then be working with fragile config which we'd like to avoid.
Ultimately we want to be able to use the default classpath:application.properties so don't want to affect existing (default) setup, but we do want to be able to use an encryptable property source as a complete replacement to the Spring one, and to have Spring load the decryption code from a file before anything else happens. Is there a way to tighter integrate loading encryptable properties earlier in the application startup and configuration?
I'm "tailoring down" my previous answer since it got deleted because it was duplicate from a different question:
This library does exactly what you need jasypt-spring-boot which is basically to allow you use the #PropertySource annotation to define your properties the same way you're use to. You just have to add an extra annotation (#EnableEncryptableProperties) to your configuration file.
It is not only limited to that, every PropertySource present in Environment will be converted to EncryptablePropertySourceWrapper, a custom wrapper that checks when a property is encrypted and decrypts it on access.
The link Dave provided in the comments section unfortunately points to nothing now, but navigating from its root I got to the following example project:
https://github.com/spring-cloud-samples/configserver (also written mostly by Dave, of course)
I think it serves as a great example for what was discussed in the comments until now.
Also, for future reference (maybe it will be done at some point), there's a Spring Framework Jira ticket for the feature of using encrypted properties: https://jira.spring.io/browse/SPR-12420

Using ServiceLocatorFactoryBean of Spring

I am creating third part login system for my web application using Oauth2 and have to support various third party Oauth2.0 service provider like
Gmail
Facebook
MSN
Yahoo
Twitter
I have already working code for these.Each service provider have a certain set of configuration which need to be created before starting Oauth process.I was thinking about using ServiceLocatorFactoryBean of Spring and create few services for each Oauth provider and based on what user has selected can fetch that specific service.
Is my approach is good enough or is it like a overuse / overcomplicated one
Edit
As per one answer, We can create a single bean with singleton scope and inject Map of required services to it so as we can fetch services from Map based on what user has selected, though approach is fine but won't that force us to load every services in Memory and no matter if we will use them or not, they will remain in Memory
Using ServiceLocatorFactoryBean is a way to do it and solves the problem of getting a bean (implementing an interface) based on a String key lookup.
The javadoc says that the class is meant mostly for injecting prototype scoped beans, but also works for other scopes altough they don't advise it.
The javadoc gives an indication that is not the use case for which the ServiceLocatorFactoryBean was created, another solution that gives the same work is to just create a singleton bean OAuthServiceProvider that returns the correct service depending on a string using just some if/elses or a map.
In the long run it would more readable, the use of the ServiceLocatorFactoryBean seems not to buy us much compared to that.

Resources