Spring Security - externalize value of "requires-channel" - spring

I need to support both HTTP and HTTPS in my Spring Security file and dynamically switch between those at runtime.
So I am trying to create properties file which would contain one of any/http/https, but that won't parse the XML config.
Spring Security config:
<sec:http entry-point-ref="portalEntryPoint">
<sec:anonymous />
<sec:intercept-url pattern = "/portal" access="IS_AUTHENTICATED_ANONYMOUSLY"
requires-channel="${user-security.login.channel}" />
<!-- rest omitted -->
</sec:http>
Properties file:
user-security.login.channel=https
I am getting following error:
Caused by: org.xml.sax.SAXParseException: cvc-enumeration-valid: Value '${user-security.login.channel}' is not facet-valid with respect to enumeration '[http, https, any]'. It must be a value from the enumeration.
I am using Spring 3 and Spring Security 2. Any ideas?

If you absolutely MUST then use profiles to configure your portal entry point. Obviously this means a lot of copy and paste in your spring config ....
Example from springsource docs :
<bean id="transferService" class="com.bank.service.internal.DefaultTransferService">
<constructor-arg ref="accountRepository"/>
<constructor-arg ref="feePolicy"/>
</bean>
<bean id="accountRepository" class="com.bank.repository.internal.JdbcAccountRepository">
<constructor-arg ref="dataSource"/>
</bean>
<bean id="feePolicy" class="com.bank.service.internal.ZeroFeePolicy"/>
<beans profile="dev">
<jdbc:embedded-database id="dataSource">
<jdbc:script location="classpath:com/bank/config/sql/schema.sql"/>
<jdbc:script location="classpath:com/bank/config/sql/test-data.sql"/>
</jdbc:embedded-database>
</beans>
<beans profile="production">
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/>
</beans>
link http://blog.springsource.com/2011/02/14/spring-3-1-m1-introducing-profile/

This was not possible in Spring Security 2, you must use Spring Security 3.0+
There was an issue filed regarding this support that was fixed prior to the release of Spring Security 3.0.

Related

After Spring upgrade from 5.2.x to 5.3.x - No mapping for GET

After upgrade from Spring 5.2.x to 5.3.x, the error message DispatcherServlet.noHandlerFound Message=No mapping for GET /sampler/
Sample code -- https://github.com/hth/sampler working fine with 5.2.12 lib
This may be related to a change where additional beans are registered with the DispatcherServlet.
Specifically, the DefaultRequestToViewNameTranslator bean is now loaded in 5.3.x, which may be transforming the URI to a view name.
You may be able to disable this behavior by setting the stripLeadingSlash, stripExtension, and stripTrailingSlash properties to false.
Try adding the following bean definition to your root-context.xml file.
<bean id="viewNameTranslator" class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator">
<property name="stripLeadingSlash" value="false" />
<property name="stripExtension" value="false" />
<property name="stripTrailingSlash" value="false" />
</bean>

Mongo DB Authentication Failed With Spring (REST)

Still now I'm using mongodb version 2.6.9 with spring (REST). In the authentication part, I have edited the mongod.conf file and enabled
auth = true
And added the below codes in spring - applicationContext.xml file
<mongo:mongo host="localhost" port="27017" id="mongo" />
<mongo:db-factory id="mongoDbFactory"
mongo-ref="mongo"
host="localhost"
port="27017"
dbname="********"
username="******"
password="********"
/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<!-- Start ## Bean mapping for Restlet service -->
<bean id="basecampComponent" class="org.restlet.ext.spring.SpringComponent">
<property name="defaultTarget" ref="autoRestletAppliction" />
</bean>
<bean id="autoRestletAppliction" class="com.jiit.restlet.frontcontroller.FirstStepsApplication">
<property name="inboundRoot" ref="router" />
</bean>
<bean name="router" class="org.restlet.ext.spring.SpringBeanRouter" />
And the jar's i have used, for the above configuration,
mongo-java-driver-2.12.1.jar &
spring-data-mongodb-1.2.0.RELEASE.jar
Now, I want to upgrade my mongodb to 3.4 Version. And I have tried to edit the mongod.conf file and enabled the security,
security.authorization: enabled
And I have added admin and mydb with users and tried to connect with mongodb client like robomongo and its works fine.
The problem is i'm not able to connect with spring to mongodb.
I have updated the jars to latest version but its not working. Could you please help me ?
I had a similar kind of problem a few days back. But then I stumbled upon this http://mongodb.github.io/mongo-java-driver/2.13/getting-started/quick-tour/ and it solved all my problems of mongodb connectivity through spring.
They have provided a proper explanations and how you could connect to your mongodb with or without credentials.

Apache Camel Spring DSL, referring to an environment variable HOSTNAME

I am using Apache Camel 2.16.0 with Spring DSL
I have a Spring context XML in which I have defined a Property PlaceHolder to read the properties from various files as follows-
<bean id="propertyPlaceholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
<property name="ignoreResourceNotFound" value="false"/>
<property name="locations">
<list>
<value>classpath:/properties/versioning.properties</value>
<value>classpath:/properties/#{inetAddress.hostName}.properties</value>
</list>
</property>
</bean>
<bean id="inetAddress" class="java.net.InetAddress" factory-method="getLocalHost"/>
The property values are used to construct other beans such as -
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="${${LIVE_}DATASOURCE_URL}"/>
<property name="username" value="${${LIVE_}DATASOURCE_USERNAME}"/>
<property name="password" value="${${LIVE_}DATASOURCE_PASSWORD}"/>
</bean>
This works fine, I can see the beans being created.
I also have another Spring Context XML in the same app which has a camel context and I want to use the some other properties defined in the same properties files. I know that camel supports Spring Property Placeholder, see below excerpts from the context -
<camelContext id="charge-process-context" xmlns="http://camel.apache.org/schema/spring">
<propertyPlaceholder id="properties"
location="classpath:/properties/versioning.properties,
properties/${env:HOSTNAME}.properties"
xmlns="http://camel.apache.org/schema/spring" />
.....
.....
</camelContext>
As part of this context, I have a route that uses https component that uses the values from the property file such as below -
<to uri="https4:{{LIVE_AUTH_RESPONSE_HOST}}:{{LIVE_AUTH_RESPONSE_PORT}}/{{LIVE_AUTH_RESPONSE_CONTEXT_PATH}}"/>
This route does not start and throws following exception -
Caused by: java.lang.IllegalArgumentException: Cannot find system environment with key: HOSTNAME
at org.apache.camel.util.FilePathResolver.resolvePath(FilePathResolver.java:54)
at org.apache.camel.component.properties.PropertiesComponent.parseLocations(PropertiesComponent.java:434)
at org.apache.camel.component.properties.PropertiesComponent.parseUri(PropertiesComponent.java:163)
at org.apache.camel.component.properties.PropertiesComponent.parseUri(PropertiesComponent.java:148)
at org.apache.camel.impl.DefaultCamelContext.resolvePropertyPlaceholders(DefaultCamelContext.java:2261)
at org.apache.camel.model.ProcessorDefinitionHelper.resolvePropertyPlaceholders(ProcessorDefinitionHelper.java:730)
at org.apache.camel.model.ProcessorDefinition.createOutputsProcessorImpl(ProcessorDefinition.java:427)
at org.apache.camel.model.ProcessorDefinition.createOutputsProcessor(ProcessorDefinition.java:413)
at org.apache.camel.model.ProcessorDefinition.createOutputsProcessor(ProcessorDefinition.java:165)
at org.apache.camel.model.ExpressionNode.createFilterProcessor(ExpressionNode.java:109)
at org.apache.camel.model.WhenDefinition.createProcessor(WhenDefinition.java:74)
at org.apache.camel.model.WhenDefinition.createProcessor(WhenDefinition.java:32)
at org.apache.camel.model.ProcessorDefinition.createProcessor(ProcessorDefinition.java:483)
at org.apache.camel.model.ChoiceDefinition.createProcessor(ChoiceDefinition.java:135)
at org.apache.camel.model.ProcessorDefinition.makeProcessorImpl(ProcessorDefinition.java:534)
at org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:495)
at org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:219)
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:1069)
Please Note: I am deploying my application as a war file on Tomcat 8 on an AWS instance.
I have a Dev Environment on Windows 10 and I have found this working on the Windows OS. I have also seen that the file FilePathResolver.java in Apache Camel 2.16 uses System.getenv(key) to obtain the value i.e. System.getenv("HOSTNAME") which returns a null on AWS instance and a correct value on Windows 10. I also tried using env:hostname (small case letters for unix) but still no luck ...
I found a solution at http://camel.apache.org/using-propertyplaceholder.html
at Bridging Spring and Camel Property Placeholders
It mentions following -
The Spring Framework does not allow 3rd party frameworks such as Apache Camel to seamless hook into the Spring property placeholder mechanism. However you can easily bridge Spring and Camel by declaring a Spring bean with the type org.apache.camel.spring.spi.BridgePropertyPlaceholderConfigurer, which is a Spring org.springframework.beans.factory.config.PropertyPlaceholderConfigurer type.

Load jndi resources into context:property-placeholder

I have the following spring config file:
<context:property-placeholder order="2"
ignore-unresolvable="true" ignore-resource-not-found="true"
location="file:///${user.home}/application.properties" />
<context:property-placeholder order="1"
ignore-unresolvable="true" ignore-resource-not-found="true"
location="file:///C:/Services/Tomcat 6.0/cms/application.properties" />
<context:property-placeholder order="3"
location="classpath:com/afrozaar/cms/service/application.properties" />
Notice how they are ordered, some are on the classpath and some are on the file system.
Now to the mix I want to add a properties file loaded via jndi. I was hoping to be able to do
<context:property-placeholder order="2"
ignore-unresolvable="true" ignore-resource-not-found="true"
location="jndi:url/application.properties" />
Unfortunately, this doesn't work, spring doesn't support the jndi prefix... AFAIK.
So, can I do something like this?
And if I can't what's my alternative. I don't want to have to convert my whole configuration to a full bean based property place holder configurer.
Not sure what you really mean with "jndi:url/application.properties". I suppose you wanted to set the path to the property file in a resource entry named "url/application.properties".
You can achieve this with the following snippets:
<bean class="org.springframework.beans.factory.config.PlaceholderConfigurerSupport">
<property name="location">
<bean id="publisherLocal" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="url/application.properties" />
<property name="expectedType" value="java.lang.String" />
</bean>
</property>
</bean>
<context:property-placeholder> has a properties-ref attribute, which can point to the bean of type Properties. So, you can load Properties in your code and declare a <context:property-placeholder> using them.

Spring DB2 JPA Entity Manager Problem

I'm trying to configure Spring, JPA and DB2 in order to have the entity manager instance to be used in my spring controllers but according how I have configured Spring this not happens.
These are the two attempts of configuration of spring:
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" />
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="em" />
</bean>
<bean id="em"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="fileUtility" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
<property name="database" value="DB2" />
<property name="showSql" value="true" />
</bean>
</property>
</bean>
the second is this:
<!-- Entity manager factory bean. -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="Sample" />
</bean>
<!-- Entity manager bean. -->
<bean id="em" factory-bean="entityManagerFactory"
factory-method="createEntityManager" />
and the entity manager is injected in this way:
<bean id="messageService" class="utilities.services.impl.MessageServiceImpl">
<property name="entityManager" ref="em" />
</bean>
but I have always this exception:
Caused by: java.lang.IllegalArgumentException: methods with same signature createEntityManager() but incompatible return types: [interface com.ibm.websphere.persistence.WsJpaEntityManager, interface org.apache.openjpa.persistence.OpenJPAEntityManagerSPI]
I don't know how can be fixed. Has anyone encountered this problem?
Thanks in advance.
[EDIT]
This is my persistence.xml:
<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">
<persistence-unit name="fileUtility"
transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<mapping-file>META-INF/mapping.xml</mapping-file>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:db2://localhost:50000/db2admin" />
<property name="openjpa.ConnectionDriverName" value="COM.ibm.db2.jdbc.app.DB2Driver" />
<property name="openjpa.ConnectionUserName" value="db2admin" />
<property name="openjpa.ConnectionPassword" value="XXXX" />
<property name="openjpa.FlushBeforeQueries" value="true"/>
<property name="openjpa.RuntimeUnenhancedClasses" value="supported" />
</properties>
</persistence-unit>
<persistence-unit name="fileUtility2" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>file_ds</jta-data-source>
<mapping-file>META-INF/mapping.xml</mapping-file>
<properties>
<property name="openjpa.Log" value="SQL=TRACE"/>
<property name="openjpa.ConnectionFactoryProperties" value="PrettyPrint=true, PrettyPrintLineLength=72"/>
</properties>
</persistence-unit>
</persistence>
WebSphere has a JPA implementation bundled. So no need to add openjpa to your lib. In fact, WebSphere is using OpenJPA, so you are not losing anything. Look here for more details
When using a jda-data-source, you need to have transaction-type="JTA". Also, you should not specify connection properties - they are specified in the datasource.
And get rid of the <provider> - the document I linked says:
If no JPA provider is configured in the element of the persistence.xml file within an EJB module, the default JPA provider that is currently configured for this server is used
I believe you're doing the wrong configuration, because you're configuring it "à la Tomcat". If you're using a Java EE application server, such as WAS, you should:
In Spring application context xml file
configure the DAO bean by a <bean> definition
configure the JNDI definition for the datasource created in the application server via a
<jee:jndi-lookup>
definition; the
name
attribute should be
persistence/XXX, where XXX shall match the
<persistence-unit name="XXX" transaction-type="JTA">
in persistence.xml file
The id attribute in the
<jee:jndi-lookup id=YYY> should point to the
name=YYY parameter of the Entity Manager definition in the DAO, this is to say,
#PersistenceContext(name=YYY) EntityManager em;
Specify
<tx:annotation-driven /> and
<tx:jta-transaction-manager />
In file
web.xml of your web app you should include a definition using the xml tag
<persistence-unit-ref> whose
<persistence-unit-ref-name> parameter shall be the
persistence/XXX JNDI name as specified in persistence.xml (shown above).
Finally, you should create a JNDI definition in the application server (AS dependant) that defines the JNDI name for the JDBC connection. This name should match the
<jta-data-source> xml tag in the persistence.xml file, and it is the only link between the JPA definition and the JDBC defined in the application server.
To round up:
Application Context Spring file
<bean class="DAO implementation class" />
<jee:jndi-lookup id="YYY" jndi-name="persistence/XXX" />
<tx:annotation-driven />
<tx:jta-transaction-manager />
persistence.xml file
<persistence-unit name="XXX" transaction-type="JTA">
<jta-data-source>jdbc/DSN</jta-data-source>
</persistence-unit>
web.xml file
...
<persistence-unit-ref>
<persistence-unit-ref-name>persistence/XXX</persistence-unit-ref-name>
</persistence-unit-ref>
...
DAO (only #PersistenceContext shown)
...
#PersistenceContext(name = "YYY")
EntityManager em;
...
Application Server: jdbc/DSN links to the connection definition, where the driver for the DBM is. Depends on both the AS and the DBM used.
Thus, you may see the connection between the DAO -> Spring Application Context file -> persistence.xml and web.xml files -> Application Server JNDI names. IF you're using a full Java EE application server (such as WAS, Weblogic or GlassFish) you don't have to use Spring interface modules; only defnitions in the app server (see Spring documentation, section 12.6.3).

Resources