I'm using Thymleaf in my spring security simple POC. Below is my sample code in home.html file.
Hello <span sec:authentication="name">User</span>!i
How to get rid of the html warning
Undefined attribute name (sec:authentication).
I Just duplicate the namespace for sec tag and html warning disappear
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org">
Joel's answer works well But this is the Proper Name Space Suggested in the Official Guidelines
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
1) Add this dependency to pom.xml:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity3</artifactId>
<version>3.0.0.BETA01</version>
</dependency>
2) Add additional dialect to templateEngine bean:
<!-- Thymeleaf Template Engine (Spring4-specific version) -->
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolvers">
<set>
<ref bean="templateResolver" />
</set>
</property>
<property name="additionalDialects">
<set>
<bean class="org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect" />
</set>
</property>
</bean>
Related
Can someone please advise how to secure a web socket endpoint using Spring Security framework?
I have an application secured with Spring Security.
One of the endpoints is a web socket.
Inside the web socket handler I need to authenticate a user making a connection to the web socket.
Specifically, I need to acquire both userid and also zone/tenant id.
If I use tag sec:http for websocket endpoint in spring-security.xml (please see the file below), this does trigger a login, and then inside web socket's #onOpen(Session session) handler
when I invoke session.getUserPrincipal(), the returned principal has a correct username inside it.
However I also need zone/tenant-id information.
I am trying to use SecurityContextHolder.getContext().getAuthentication() which should contain it, but the call returns null.
Apparently, sec:http does not cause Authentication object to be created for web socket requests.
I had been referred to
http://docs.spring.io/autorepo/docs/spring-security/4.1.x/reference/html/websocket.html
http://docs.spring.io/autorepo/docs/spring-security/4.1.x/reference/html/appendix-namespace.html#nsa-websocket-security
that seems to advise that to get an authenticator with zone information in it for a websocket endpoint, I need to add the following section to spring-security.xml:
<sec:websocket-message-broker>
<sec:intercept-message pattern="/WebSocket.svc" access="isAuthenticated()" />
</sec:websocket-message-broker>
Yet, when I add it and trying to start the application it fails with the following traceback/message:
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Security namespace does not support decoration of element [websocket-message-broker]
Offending resource: ServletContext resource [/WEB-INF/spring-security.xml]
at org.springframework.beans.factory.parsing.FailFastProblemReporter.fatal(FailFastProblemReporter.java:60) ~[spring-beans-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.beans.factory.parsing.ReaderContext.fatal(ReaderContext.java:68) ~[spring-beans-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.beans.factory.parsing.ReaderContext.fatal(ReaderContext.java:55) ~[spring-beans-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.security.config.SecurityNamespaceHandler.reportUnsupportedNodeType(SecurityNamespaceHandler.java:144) ~[spring-security-config-4.1.2.RELEASE.jar:4.1.2.RELEASE]
I am using Spring Security 4.1.2, and 4.3.1 for master Spring.
It is also unclear from Spring documentation whether sec:websocket-message-broker and sec:http should be used in conjunction for the web socket endpoint or are mutually exclusive.
Thanks for advice.
Sergey
P.S. My spring-security.xml looks like this:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2
http://www.springframework.org/schema/security/spring-security-oauth2-1.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<sec:http pattern="/Consumer.svc/**" create-session="never"
entry-point-ref="oauthAuthenticationEntryPoint"
access-decision-manager-ref="accessDecisionManager"
authentication-manager-ref="authenticationManager"
use-expressions="true">
<sec:anonymous enabled="false" />
<sec:intercept-url pattern="/Consumer.svc/**" access="isAuthenticated()" />
<sec:custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<sec:access-denied-handler ref="oauthAccessDeniedHandler" />
</sec:http>
<sec:http pattern="/WebSocket.svc" create-session="never"
entry-point-ref="oauthAuthenticationEntryPoint"
access-decision-manager-ref="accessDecisionManager"
authentication-manager-ref="authenticationManager"
use-expressions="true">
<sec:anonymous enabled="false" />
<sec:intercept-url pattern="/WebSocket.svc" access="isAuthenticated()" />
<sec:custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<sec:access-denied-handler ref="oauthAccessDeniedHandler" />
</sec:http>
<sec:websocket-message-broker>
<sec:intercept-message pattern="/WebSocket.svc" access="isAuthenticated()" />
</sec:websocket-message-broker>
<bean id="oauthAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
</bean>
<bean id="oauthWebExpressionHandler"
class="org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler">
</bean>
<bean id="accessDecisionManager"
class="org.springframework.security.access.vote.UnanimousBased">
<constructor-arg>
<list>
<bean class="org.springframework.security.web.access.expression.WebExpressionVoter">
<property name="expressionHandler" ref="oauthWebExpressionHandler" />
</bean>
<bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
</list>
</constructor-arg>
</bean>
<sec:authentication-manager alias="authenticationManager"/>
<oauth:resource-server id="resourceServerFilter"
resource-id="springsec" token-services-ref="offlineTokenServices" />
<bean id="oauthAccessDeniedHandler"
class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />
<!-- ... also some other elements here ... -->
</beans>
It was necessary to add the following to pom.xml:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-messaging</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${spring.version}</version>
</dependency>
And this to spring-security.xml:
<bean id="springSecurityMessagePathMatcher"
class="org.springframework.util.AntPathMatcher"/>
Now Spring does not throw an exception at startup and parses spring-security.xml fine, but it does not work either. SecurityContextHolder.getContext().getAuthentication() still returns null.
Our Webflow (2.3.1) application is claiming a lot of memory for each new flow that we open through the browser.
The screenshot below shows our application's memory use. When the application starts it takes an initial 400 Mb. After that we open 4 individual, identical Webflow TEST pages in the browser which each claim about 90Mb of extra memory..
Each test page is started from its own simple flow definition:
<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/webflow"
xsi:schemaLocation="http://www.springframework.org/schema/webflow
http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd" start-state="start">
<view-state id="start" view="test/test1">
</view-state>
<end-state id="end"/>
<bean-import resource="../flow-beans.xml"/>
</flow>
The JSP test pages are also very simple, just empty with one line of text.
When we currently set the JVM memory to 1.5Gb the application eventually crashes on the server with OutOfMemoryExceptions after opening about 15 different flows. 1.5 Gb seems a bit much, regarding the low complexity of our screens..
We are wondering if the amount of memory Webflow seems to claim for these simple flows/pages is expected and if we should therefore just assign more memory to the server JVM. If not, we would like to know how we can decrease this memory usage.
Below is our entire webflow configuration.
We have tried adding a flow-execution-repository tag and played around with the max-executions-snapshots and max-executions values, but even the most conservative settings don't change the memory usage we are seeing.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:webflow="http://www.springframework.org/schema/webflow-config"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/webflow-config
http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Launches new flow executions and resumes existing executions. -->
<webflow:flow-executor id="flowExecutor" flow-registry="flowRegistry">
</webflow:flow-executor>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:our.properties" />
<property name="placeholderPrefix" value="$xxxx"></property>
</bean>
<tx:annotation-driven transaction-manager="$xxxx{txManager}" />
<!-- Creates the registry of flow definitions for this application -->
<webflow:flow-registry id="flowRegistry" flow-builder-services="flowBuilderServices">
<webflow:flow-location-pattern value="classpath:flows/**/*-flow.xml" />
</webflow:flow-registry>
<bean id="viewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
<property name="viewResolvers" ref="viewResolver" />
</bean>
<bean id="expressionParser" class="org.springframework.expression.spel.standard.SpelExpressionParser">
<constructor-arg name="configuration">
<bean class="org.springframework.expression.spel.SpelParserConfiguration">
<constructor-arg name="autoGrowCollections" value="true" />
<constructor-arg name="autoGrowNullReferences" value="false" />
</bean>
</constructor-arg>
</bean>
<bean id="webflowExpressionParser" class="org.springframework.webflow.expression.spel.WebFlowSpringELExpressionParser">
<constructor-arg name="expressionParser" ref="expressionParser" />
</bean>
<webflow:flow-builder-services id="flowBuilderServices" view-factory-creator="viewFactoryCreator" validator="validator" expression-parser="webflowExpressionParser"/>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<bean id="projectVersion" class="our.company.versions.ProjectVersionUtil">
<property name="xxxxVersion" value="$xxxx{xxxx.version}" />
<property name="systemConfigurationDao">
<ref bean="SystemConfigurationDao"/>
</property>
</bean>
</beans>
When Spring Web Flow starts a new flow it basically constructs a new BeanFactory which loads the xml file and imports any additional xml files. The newly constructed BeanFactory has the context of the DispatcherServlet as its parent.
Now the problem with this is that a the bean factory constructs instances of all the beans even those defined in imported XML files.
<bean-import resource="../flow-beans.xml"/>
If there are a lot of beans in there those will be duplicated for each flow instance. In general you don't want your all of your beans duplicated and stored in the users sessions.
Remove the singleton beans from the flow-beans.xml and put them in the normal application context, they are still referable from within the flow definition. Or you could simply add the flow-beans.xml to the list of files loaded at startup of your application.
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>
Currently i am implementing web services using Spring-ws . Here i am struck with xsd validation . For xsd validation i am using the following configruation
<bean id="validatingInterceptor" class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor">
<property name="xsdSchema" ref="schema" />
<property name="validateRequest" value="true" />
<property name="validateResponse" value="true" />
</bean>
<bean id="schema" class="org.springframework.xml.xsd.SimpleXsdSchema">
<property name="xsd" value="/WEB-INF/ProductSchema.xsd" />
</bean>
Here i am passing the xsd file during bean initialization . Is there any way for me to send this(ProductSchema.xsd) xsd file dynamically. Because I will comes to know which xsd file needs to send based on the input payload.
Please help me. Thanks in advance
I don't know how many XSD's you have, but perhaps you can define imports in ProductSchema.xsd to include the others. That's at least how I've got it set up.
For example:
<import namespace="http://namespace" schemaLocation="data.xsd" />
I'm not quite sure of what you are trying to do.
But you can make different endpoints/methods that matches different payloads by annotating the handler method with a localPart that matches the name of an element i the payload:
#Endpoint
public class MyEndpoint {
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "NameOfMyXmlRequestElement")
#ResponsePayload
public MyResponse handleMyRequest(#RequestPayload MyRequest MyRequest) throws Exception {
...
A recived request can then be unmarshalled/validated using a specific schema:
<bean id="myJaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>mydomain.model.oxm.MyRequest</value>
<value>mydomain.model.oxm.MyResponse</value>
</list>
</property>
<property name="schema" ref="MyServiceSchema" />
</bean>
<bean id="MyServiceSchema" class="org.springframework.core.io.ClassPathResource">
<constructor-arg value="WEB-INF/schemas/MyService.xsd" />
</bean>
The MyRequest class must be annotated to work with the Jaxb2marshaller, #XmlRootElement(name="MyRequest") etc...
I'm quite new to Spring Framework. Could someone please help me understand the spring configuration below?
<?xml version="1.0"?>
<configuration>
<spring>
<context>
<resource uri="config://spring/objects" />
</context>
<objects xmlns="http://www.springframework.net">
<object type="Test.aspx">
<property name="AService" ref="AService" />
<property name="BService" ref="BService" />
</object>
</objects>
</spring>
</configuration>
Basically questions in my mind are:
What does this line means:
<resource uri="config://spring/objects" />
and this:
<object type="Test.aspx">
<property name="AService" ref="AService" />
<property name="BService" ref="BService" />
</object>
Does config: means configuration file?
Does ref means Classes in C#?
<resource uri="config://spring/objects" /> means that the spring container should read a configuration section from an application configuration file (app.config or web.config).
<object ... is an object definition; this defines an object in your container. An object can have dependencies. In your case, the Test.aspx page has properties named AService and BService. The container will set these properties to the objects defined elsewhere in your container.
What might be a bit confusing here is the double usage of ="AService" in <property name="AService" ref="AService" />:
name=: refers to the name of the property on your class Test, there is a property defined as public IMyService AService { get; set; }
ref= : refers to another object defined in your container, there is an object definition like <object id="AService" type="MyNamespace.MyClass, MyAssembly" /> somewhere in your configuration.
The "Instantiating the container" section of the spring docs does a good job of explaining this further.