spring-messaging xml config with stomp and spring-sessions - spring-websocket

I'm trying to set up WebSockets with spring-messaging using stomp, and using redis-backed sessions with spring-session. Our application context is wired via xml, and spring-session is working with the non-websocket portion of the application. The relevant config for websocket is as follows
<websocket:message-broker application-destination-prefix="/streaming" >
<websocket:stomp-endpoint path="/data">
<websocket:sockjs session-cookie-needed="false" />
</websocket:stomp-endpoint>
<websocket:stomp-broker-relay prefix="/topic" relay-host="${jms_hostname}" relay-port="${jms_stomp_port}" />
<websocket:client-inbound-channel>
<websocket:interceptors>
<ref bean="sessionRepoMessageInterceptor"/>
<ref bean="authenticationValidationInterceptor" />
<ref bean="selectorValidationInterceptor" />
<ref bean="selectorQuotingInterceptor" /> <!-- comes after we have validated the selector, we now shim it so JMS understands it -->
</websocket:interceptors>
</websocket:client-inbound-channel>
</websocket:message-broker>
I have defined what I think are the necessary beans for spring-session's integration with web sockets here:
<bean id="redisSessionBackedWebsocketHandler" class="org.springframework.session.web.socket.server.">
</bean>
<bean id="sessionRepoMessageInterceptor" class="org.springframework.session.web.socket.server.SessionRepositoryMessageInterceptor">
</bean>
<bean id="webSocketRegistryListener" class="org.springframework.session.web.socket.handler.WebSocketRegistryListener">
</bean>
but I'm not sure where I would wire them in to the web socket configuration, and have not been able to find any doc on how to do it this way.
Thoughts?

The Spring Session WebSocket contains the config just only for the Java & Annotation variant.
And according to the Spring Session Docs the AbstractSessionWebSocketMessageBrokerConfigurer does the stuff for seamless integration between Spring Session and Spring WebSockets. However there we can see some paragraph, what it does:
To hook in the Spring Session support, we need to ensure ...
To be honest it isn't so easy to configure that stuff from XML.
Feel free to follow with the issue: https://github.com/spring-projects/spring-session/issues/101

Related

Spring SAML configuration is breaking other http connections

I am using Spring SAML to implement single sign on in my application. Evreything is integrated and works properly from SSO perspective.
Another service of my application which also uses HTTP client post via Axis started failing with the following error
{http://xml.apache.org/axis/}stackTrace:javax.net.ssl.SSLPeerUnverifiedException: SSL peer failed hostname validation for name: null
I have looked into the answer provided the link
Spring Security SAML + HTTPS to another page and follow the same but to no avail.
Below is the configuration for TLSProtocolSocketFactory
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="org.apache.commons.httpclient.protocol.Protocol"/>
<property name="targetMethod" value="registerProtocol"/>
<property name="arguments">
<list>
<value>https</value>
<bean class="org.apache.commons.httpclient.protocol.Protocol">
<constructor-arg value="https"/>
<constructor-arg>
<bean class="org.springframework.security.saml.trust.httpclient.TLSProtocolSocketFactory">
<constructor-arg ref="keyManager"/>
<constructor-arg><null/></constructor-arg>
<constructor-arg value="allowAll"/>
</bean>
</constructor-arg>
<constructor-arg value="443"/>
</bean>
</list>
</property>
</bean>
I have imported the cert of the other service in samlKeystore.jks as well.
Any help in the issue will be apreciated
I think this may be what you're looking for: Source
You are using bean TLSProtocolConfigurer which changes trusted certificates and hostname verification of the HTTPS protocol in the HTTP Client. You can revert behaviour of the HTTP Client back to defaults by removing this bean. You will then need to make sure that certificates used by entities from which you load metadata (https://idp.ssocircle.com/idp-meta.xml) are trusted in your cacerts, or use an endpoints without https (http://idp.ssocircle.com/idp-meta.xml).
Alternatively, you can disable hostname verification by setting property sslHostnameVerification to allowAll on bean TLSProtocolConfigurer. You will also need to make sure that the HTTPS certificate of https://www.somepage.com (or its CA) is included in the samlKeystore.jks (see Spring SAML manual).
You can find more details on the TLSProtocolConfigurer bean in the Spring SAML manual, chapter HTTP-based metadata provider with SSL.
The issue is in checkNames() function of PKIXX509CredentialTrustEngine where we are checking the trustedNames collection only for null instead of "null or Empty".Even though we are passing the value for trustedNames as null in TLSProtocolSocketFactory's getPKIXResolver() method to create StaticPKIXValidationInformatonResolver, the constructor of this class reinitialized the trustedNames collection to an empty collection.Changing the line from if(trustedNames == null) to if(trustedNames == null || trustedNames.isEmpty()) fixed the problem for me.

Configure Spring Security to return 403 for REST URLs and redirect to login for other URLs

My web application has a bunch "normal" resources (html pages etc) and also some REST resources which are called from JavaScript by the previously mentioned html pages.
If there is a session timeout the user gets redirected to the login form. That's great for the "normal" resources, but not for the REST resources. I'll just need a 403 response there so that the JavaScript can take over and ask the user to reauthenticate.
There are countless examples on the web how to configure each of those, but I could not find an example on how to combine the methods. All my API URLs start with "/api/", so I'll need the 403 for all those URLs and the redirect for all the remaining URLs. How do I set this up?
It took me a little bit of Spring source code study to get this to work. You can set up an authentication entry point as follows:
<bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint">
<!-- this is the configuration for /api/ URLs -->
<constructor-arg>
<map>
<entry>
<key>
<bean class="org.springframework.security.web.util.matcher.RegexRequestMatcher">
<constructor-arg value="^/api/.*" /><!-- match URLs starting with "/api/" -->
<constructor-arg><null /></constructor-arg><!-- no matter what the HTTP method is -->
</bean>
</key>
<!-- if the key above has matched, send 403 response -->
<bean class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />
</entry>
</map>
</constructor-arg>
<!-- and in the default case just redirect to login form -->
<property name="defaultEntryPoint">
<bean class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<constructor-arg value="/spring_security_login" />
</bean>
</property>
</bean>
This can then be used in the Sping Security configuration:
<http ... entry-point-ref="authenticationEntryPoint">
I think that you should just have two different <http pattern="{...}" ...> entities, because, ok, you solved the problem with the redirect, but what about csrf protection? And other problems that I can't think of of the top of my head.

Error registering camel's ftp jpa Idempotent repository

I'm trying to implement jpa idempotent repository just as described here http://camel.apache.org/file2.html, but i'm getting a Mbean export error.
On my application-context.xml i've the following section.
<bean id="mvStore" class="org.apache.camel.processor.idempotent.jpa.JpaMessageIdRepository" lazy-init="false">
<!-- Here we refer to the spring jpaTemplate -->
<constructor-arg index="0" ref="jpaTemplate" />
<!-- This 2nd parameter is the name (= a cateogry name). You can have different repositories with different names -->
<constructor-arg index="1" value="FileConsumer" />
</bean>
<context:mbean-server id="mbeanServer" />
<context:mbean-export server="mbeanServer" registration="replaceExisting" default-domain="br.com.touchtec"/>
If I remove the above section than the server (tomcat) starts just fine. Can anybody help me on this?
Here's the stack:
Caused by: org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [org.apache.camel.processor.idempotent.jpa.JpaMessageIdRepository#6df960c4] with key 'mvStore'; nested exception is javax.management.MalformedObjectNameException: Key properties cannot be empty
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:602)
at org.springframework.jmx.export.MBeanExporter.registerBeans(MBeanExporter.java:527)
at org.springframework.jmx.export.MBeanExporter.afterPropertiesSet(MBeanExporter.java:413)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 50 more
Caused by: javax.management.MalformedObjectNameException: Key properties cannot be empty
at javax.management.ObjectName.construct(ObjectName.java:467)
at javax.management.ObjectName.<init>(ObjectName.java:1403)
at javax.management.ObjectName.getInstance(ObjectName.java:1285)
at org.springframework.jmx.support.ObjectNameManager.getInstance(ObjectNameManager.java:62)
at org.springframework.jmx.export.naming.MetadataNamingStrategy.getObjectName(MetadataNamingStrategy.java:114)
at org.springframework.jmx.export.MBeanExporter.getObjectName(MBeanExporter.java:728)
at org.springframework.jmx.export.MBeanExporter.registerBeanInstance(MBeanExporter.java:631)
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:592)
... 54 more
First of all, I hope you're clear on the fact the jmx part is not necessary to make the Idempotent Repository work. Your error is a pure JMX/Spring error, not linked to Camel.
If you want to use an MBeanExporter, you should read the official documentation on Spring JMX to have a better understaking of this matter.
Your MBeanExporter definition might look like
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="bean:name=mvStore" value-ref="mvStore"/>
</map>
</property>
<property name="server" ref="mbeanServer"/>
</bean>

How to use J2eePreAuthenticatedProcessingFilter and a custom authentication provider?

I want my Spring application to try two pre-authentication methods (Siteminder and Java EE container authentication).
If either of these filters locates a username - I want to check that username against my database of users and assign roles based on what I see in the database. (I have an implementation of AuthenticationUserDetailsService, which does that for me.)
If not - show a login page to the user. Check the credentials they enter in the form against my database of users.
The Siteminder integration is working. The login form is working too. My problem is with the Java EE pre-authentication. It never kicks in.
My applicationContext-security.xml:
<!-- HTTP security configurations -->
<sec:http auto-config="true" use-expressions="true">
<sec:form-login login-processing-url="/resources/j_spring_security_check" always-use-default-target="true" default-target-url="/" login-page="/login"
authentication-failure-url="/login?login_error=t" />
<sec:logout logout-url="/resources/j_spring_security_logout" />
<sec:access-denied-handler error-page="/accessDenied" />
<sec:remember-me user-service-ref="customUserDetailsService" token-validity-seconds="86400" key="OptiVLM-VaultBalance" />
<sec:custom-filter position="PRE_AUTH_FILTER" ref="siteminderFilter"/>
<sec:custom-filter after="PRE_AUTH_FILTER" ref="jeePreAuthenticatedFilter"/>
<!-- various intercept-url elements here, skipped for brevity -->
</sec:http>
<!-- Authentication Manager -->
<sec:authentication-manager alias="authenticationManager">
<!-- J2EE container pre-authentication or Siteminder -->
<sec:authentication-provider ref="customPreAuthenticatedAuthenticationProvider" />
<!-- Default provider -->
<sec:authentication-provider user-service-ref="customUserDetailsService" />
</sec:authentication-manager>
<!-- Siteminder pre-authentication -->
<bean id="siteminderFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
<property name="principalRequestHeader" value="SM_USER" />
<property name="authenticationManager" ref="authenticationManager" />
<property name="exceptionIfHeaderMissing" value="false" />
</bean>
<!-- J2EE pre-authentication -->
<bean id="jeePreAuthenticatedFilter" class="org.springframework.security.web.authentication.preauth.j2ee.J2eePreAuthenticatedProcessingFilter">
<property name="authenticationManager" ref="authenticationManager" />
</bean>
<!-- Custom pre-authentication provider -->
<bean id="customPreAuthenticatedAuthenticationProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<property name="preAuthenticatedUserDetailsService" ref="customAuthenticationUserDetailsService" />
</bean>
I have Java 2 security enabled in Websphere, and I am logged in as 'admin5'. (I have a user with this username in my user database.) But when I access the application, there is never a call to the 'customAuthenticationUserDetailsService' bean to verify the username. I know this, because 'customAuthenticationUserDetailsService' does extensive logging which clearly shows what it is doing. When I am using the Siteminder pre-authentication - the 'customAuthenticationUserDetailsService' works just fine, I get some trace output in the log. But not for the J2EE authentication...
My guess is that one of these things is happening:
a) Java EE pre-authentication filter is not locating the username, so it never calls the authentication manager
b) Java EE pre-authentication filter works fine, but my custom authentication provider is never called by the authentication manager for some reason
By the way, the default authentication provider, which uses 'customUserDetailsService' does not kick in either. Again, I can tell that because there is no output from 'customUserDetailsService' in the log.
Can you advise on what could be the problem here? If not a solution, then a suggestion on how to approach this would be greatly appreciated.
OK, I figured this out. The problem is that even though I had J2EE security setup in Websphere and was authenticated, my web.xml contained no security constraints. Because of this, Websphere was not supplying the principal for my requests. This is apparently an intentional feature. If you are not accessing a protected URL, you should not need the pre-authentication information.
To overcome this, I added a security constraint to my web.xml, which allowed ALL users to access the resources. Effectively, the resources were not secured, but still - there was a constraint now.
This is it:
<security-constraint>
<web-resource-collection>
<web-resource-name>All areas</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>*</role-name>
</auth-constraint>
</security-constraint>
This tricks the Websphere into filling in the user principal information in the request.
Thank you #Ralph for his comments on this this question: request.getUserPrincipal() got null

Creating a custom authentication with Acegi/Spring Security

I'm having trouble discovering exactly what I need to implement in order to use a custom authentication method with my web application using Spring Security. I have a Grails application with the Spring Security plugin that currently uses the standard user/password authentication with a browser form. This is working correctly.
I need to implement a mechanism alongside of this that implements a type of MAC authentication. If the HTTP request contains several parameters (e.g. a user identifier, timestamp, signature, etc.) I need to take those parameters, perform some hashing and signature/timestamp comparisons, and then authenticate the user.
I'm not 100% sure where to start with this. What Spring Security classes do I need to extend/implement? I have read the Reference Documentation and have an okay understanding of the concepts, but am not really sure if I need a Filter or Provider or Manager, or where/how exactly to create Authentication objects. I've messed around trying to extend AbstractProcessingFilter and/or implement AuthenticationProvider, but I just get caught up understanding how I make them all play nicely.
Implement a custom AuthenticationProvider which gets all your authentication information from the Authentication: getCredentials(), getDetails(), and getPrincipal().
Tie it into your Spring Security authentication mechanism using the following configuration snippet:
<bean id="myAuthenticationProvider" class="com.example.MyAuthenticationProvider">
<security:custom-authentication-provider />
</bean>
This step is optional, if you can find a suitable one from standard implementations. If not, implement a class extending the Authentication interface on which you can put your authentication parameters:
(e.g. a user identifier, timestamp, signature, etc.)
Extend a custom SpringSecurityFilter which ties the above two classes together. For example, the Filter might get the AuthenticationManager and call authenticate() using your implementation of Authentication as input.
You can extend AbstractAuthenticationProcessingFilter as a start.
You can reference UsernamePasswordAuthenticationFilter which extends AbstractAuthenticationProcessingFilter. UsernamePasswordAuthenticationFilter implements the standard Username/Password Authentication.
Configure your Spring Security to add or replace the standard AUTHENTICATION_PROCESSING_FILTER. For Spring Security Filter orders, see http://static.springsource.org/spring-security/site/docs/3.0.x/reference/ns-config.html#filter-stack
Here is a configuration snippet for how to replace it with your implementation:
<beans:bean id="myFilter" class="com.example.MyAuthenticationFilter">
<custom-filter position="AUTHENTICATION_PROCESSING_FILTER"/>
</beans:bean>
I have recently put up a sample application that does custom authentication with Spring Security 3.
The source code is here.
More details are in this blog post.
Here is an example of securityContext.xml configuration file using custom autenticationFilter (extending AUTHENTICATION_PROCESSING_FILTER) and authenticationProvider. The user authentication data is provided by jdbc connection. Configuration is for Spring Security 2.0.x
<?xml version="1.0" encoding="UTF-8"?>
<sec:global-method-security />
<sec:http auto-config="false" realm="CUSTOM" create-session="always" servlet-api-provision="true"
entry-point-ref="authenticationProcessingFilterEntryPoint" access-denied-page="/notauthorized.xhtml"
session-fixation-protection="migrateSession">
<sec:port-mappings>
<sec:port-mapping http="80" https="443" />
</sec:port-mappings>
<sec:anonymous granted-authority="ROLE_ANONYMOUS" username="Anonymous" />
<sec:intercept-url pattern="/**" access="ROLE_ANONYMOUS, ROLE_USER" />
<sec:logout logout-url="/logoff" logout-success-url="/home.xhtml" invalidate-session="false" />
</sec:http>
<bean id="authenticationProcessingFilterEntryPoint" class="org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint">
<property name="loginFormUrl" value="/login.xhtml" />
<property name="forceHttps" value="false" />
</bean>
<bean id="authenticationProcessingFilter" class="mypackage.CustomAuthenticationProcessingFilter">
<sec:custom-filter position="AUTHENTICATION_PROCESSING_FILTER" />
<property name="defaultTargetUrl" value="/" />
<property name="filterProcessesUrl" value="/logon" />
<property name="authenticationFailureUrl" value="/loginError.xhtml" />
<property name="alwaysUseDefaultTargetUrl" value="false" />
<property name="authenticationManager" ref="authenticationManager" />
</bean>
<jee:jndi-lookup id="securityDataSource" jndi-name="jdbc/DB_DS" />
<bean id="myUserDetailsService" class="mypackage.CustomJdbcDaoImpl">
<property name="dataSource" ref="securityDataSource" />
<property name="rolePrefix" value="ROLE_" />
</bean>
<bean id="apcAuthenticationProvider" class="mypackage.CustomDaoAuthenticationProvider">
<property name="userDetailsService" ref="myUserDetailsService" />
<sec:custom-authentication-provider />
</bean>
<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<list>
<ref local="apcAuthenticationProvider" />
</list>
</property>
</bean>
</beans>

Resources