Token based authentication with spring security - java

I am trying to implement token based authentication with spring security.
Planning to use Header based authentication token.
My web.xml file is this
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>api</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/api-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>api</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>0</session-timeout>
</session-config>
</web-app>
my admin servlet is 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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<context:property-placeholder location="/WEB-INF/database.properties" />
<context:component-scan base-package="com.netphenix.employee.api" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="defaultContentType" value="text/html"/>
<property name="ignoreAcceptHeader" value="true"/>
<property name="favorPathExtension" value="true"/>
<property name="order" value="1"/>
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<!-- Use tiles2 for views -->
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<ref bean="jsonView"/>
</list>
</property>
</bean>
<bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="contentType" value="application/json;charset=UTF-8"/>
</bean>
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${database.driver}" />
<property name="jdbcUrl" value="${database.url}" />
<property name="user" value="${database.user}" />
<property name="password" value="${database.password}" />
<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
<property name="minPoolSize" value="${jdbc.minPoolSize}" />
<property name="maxStatements" value="${jdbc.maxStatements}" />
<property name="testConnectionOnCheckout" value="${jdbc.testConnection}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.netphenix.employee.model"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
<bean id="freemarkerConfigFactory" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
<property name="templateLoaderPath" value="classpath:templates/"/>
</bean>
<!--
<bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
<bean id= "authenticationManager" class= "org.springframework.security.authentication.ProviderManager">
<constructor-arg>
<list>
<bean class= "org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
</list>
</constructor-arg>
</bean>-->
<sec:http>
<sec:intercept-url pattern="/login.html"/>
<sec:intercept-url pattern="/api/**" access="ROLE_ADMIN" />
<sec:form-login login-page="/login.html"
authentication-failure-url="/login.html?error=failed"
login-processing-url="/login-please.html" />
<sec:logout logout-url="/logoff-please.html"
logout-success-url="/logoff.html" />
</sec:http>
<sec:authentication-manager>
<sec:authentication-provider user-service-ref="userDetailsService">
<sec:password-encoder hash="md5"/>
</sec:authentication-provider>
</sec:authentication-manager>
<sec:http auto-config="true">
<sec:intercept-url pattern="/api/**" access="ROLE_ADMIN" />
<sec:logout logout-success-url="/login" />
</sec:http>
<sec:authentication-manager>
<sec:authentication-provider>
<sec:user-service>
<sec:user name="mkyong" password="password" authorities="ROLE_USER" />
<sec:user name="eclipse" password="password" authorities="ROLE_ADMIN" />
</sec:user-service>
</sec:authentication-provider>
</sec:authentication-manager>
<sec:global-method-security pre-post-annotations="enabled" />
</beans>
EDIT: UserDetailsService
#Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private UserDao userDao;
#Autowired
private Assembler assembler;
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
UserDetails userDetails = null;
// User userEntity = userDao.getUser(username);
User userEntity = new User();
userEntity.setUsername("admin");
userEntity.setPassword("$2a$10$hbxecwitQQ.dDT4JOFzQAulNySFwEpaFLw38jda6Td.Y/cOiRzDFu");
if (userEntity == null)
throw new UsernameNotFoundException("user not found");
return assembler.buildUserFromUserEntity(userEntity);
}
}
API works okay. but its not getting authenticated. Which means, even for the url which requires ROLE_ADMIN also works without any authentication. Any pointer towards fixing this will be helpful.

Related

Valid XML document must have a root tag

I find stackoverflow with it, and find a post in Android, but I don't think this is fit me.
Selector for button error "Valid XML document must have a root tag"
My snapshot is below:
And my code in spring_datasource.xml:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<!--资源载入器 -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>
</list>
</property>
</bean>
<!--数据连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${connection.url}" />
<property name="username" value="${connection.username}" />
<property name="password" value="${connection.password}" />
<property name="initialSize" value="${connection.initialSize}" />
<property name="minIdle" value="${connection.minIdle}" />
<property name="maxActive" value="${connection.maxActive}" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
</bean>
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 基于注解的事物管理 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 当在web.xml 中DispatcherServlet使用<url-pattern>/</url-pattern> 映射时,
能映射静态资源(当Spring Web MVC框架没有处理请求对应的控制器时(如一些静态资源),
转交给默认的Servlet来响应静态文件,否则报404找不到资源错误,)。-->
<mvc:default-servlet-handler />
<!-- spring和hibernate整合 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
${hibernate.dialect}
</prop>
<prop key="hibernate.show_sql">
${hibernate.show_sql}
</prop>
<prop key="hibernate.format_sql">
${hibernate.format_sql}
</prop>
<prop key="hibernate.hbm2ddl.auto">
${hibernate.hbm2ddl.auto}
</prop>
<prop key="hibernate.jdbc.batch_size">
${hibernate.jdbc.batch_size}
</prop>
<prop key="hibernate.autoReconnect">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.ldl.vision86.common.basis.entity</value>
<value>com.ldl.vision86.business.entity</value>
</list>
</property>
</bean>
<!-- 定时器配置
task:executor/#pool-size:可以指定执行线程池的初始大小、最大大小
task:executor/#queue-capacity:等待执行的任务队列的容量
task:executor/#rejection-policy:当等待队已满时的策略,分为丢弃、由任务执行器直接运行等方式
-->
<task:scheduler id="scheduler" pool-size="10" />
<task:executor id="executor" keep-alive="3600" pool-size="100-200"
queue-capacity="500" rejection-policy="CALLER_RUNS" />
<task:annotation-driven executor="executor" scheduler="scheduler" />
</beans>
I don't know where is the issue.
Your XML is no problem.
Try to Click the Create Spring facet.

Tomcat startup takes huge time with my Spring application

I have Spring project which produces 42MB war file. Whenever I deploy it in a server it is taking more than an hour with tomcat 7. Even in development environment it is consuming more than 20 mins in the local environment if we make any changes in it.
I suspect I have a major mistake.
<?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:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<context:component-scan base-package="com.abc.xyz.server.filters" />
<context:component-scan base-package="com.abc.xyz.server.utils" />
<context:component-scan base-package="com.abc.xyz.server.application.Bean" />
<context:component-scan
base-package="com.abc.xyz.server.application.controllers" />
<context:component-scan
base-package="com.abc.xyz.server.application.services" />
<jpa:repositories
base-package="com.abc.xyz.server.application.repositories" />
<mvc:annotation-driven>
<mvc:message-converters>
<!-- Use the HibernateAware mapper instead of the default -->
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean
class="com.abc.xyz.server.utils.HibernateAwareObjectMapper" />
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- <bean id="jdbcEmployeeDAO" class="com.abc.xyz.server.application.model.dao.JDBCEmployeeDAOImpl">
</bean> -->
<bean id="jdbcProperty"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/WEB-INF/application.properties</value>
</property>
</bean>
<bean id="abstractDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:username="${jdbc.username}" p:password="${jdbc.password}">
<property name="initialSize" value="0" />
<property name="maxIdle" value="1" />
<property name="minIdle" value="0" />
<property name="validationQuery" value="SELECT 1" />
<property name="testOnBorrow" value="true" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="180000" />
<property name="numTestsPerEvictionRun" value="100" />
<property name="minEvictableIdleTimeMillis" value="120000" />
<property name="removeAbandonedTimeout" value="60" />
<property name="logAbandoned" value="true" />
<property name="maxActive" value="30" />
<property name="maxWait" value="3000" />
<property name="removeAbandoned" value="true" />
</bean>
<bean id="concreteDataSourceOne" parent="abstractDataSource"
p:url="${jdbc.databaseurlOne}" />
<bean id="concreteDataSourceTwo" parent="abstractDataSource"
p:url="${jdbc.databaseurlTwo}" />
<bean id="concreteDataSourceDev" parent="abstractDataSource"
p:url="${jdbc.databaseurlDev}" />
<bean id="concreteDataSourceGlace" parent="abstractDataSource"
p:url="${jdbc.databaseurlGlace}" />
<bean id="dataSource"
class="com.abc.xyz.server.datasource.TennantAwareDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="database2" value-ref="concreteDataSourceTwo" />
<entry key="database1" value-ref="concreteDataSourceOne" />
<entry key="dev" value-ref="concreteDataSourceDev" />
<entry key="glace" value-ref="concreteDataSourceGlace" />
</map>
</property>
<property name="defaultTargetDataSource" ref="concreteDataSourceGlace" />
</bean>
<bean id="objectmapper" class="com.fasterxml.jackson.databind.ObjectMapper"></bean>
<bean id="EntityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:persistenceUnitName="PersistenceUnit" p:dataSource-ref="dataSource">
<!-- THIS IS WHERE THE MODELS ARE -->
<property name="packagesToScan"
value="com.abc.xyz.server.application.models" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:showSql="${hibernate.show_sql}" p:generateDdl="false"
p:databasePlatform="${hibernate.dialect}" />
</property>
</bean>
<!-- Ecache related stuff -->
<!-- <cache:annotation-driven /> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cache-manager-ref="ehcache"/> <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:config-location="classpath:ehcache.xml" p:shared="true"/> -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="EntityManagerFactory" />
</bean>
<tx:annotation-driven />
<bean id="sessionMap" class="com.abc.xyz.server.utils.SessionMap"
scope="session">
<!-- this next element effects the proxying of the surrounding bean -->
<aop:scoped-proxy />
</bean>
<!-- Configuration Bean -->
<mvc:default-servlet-handler />
<mvc:interceptors>
<bean class="com.abc.xyz.server.utils.EMRRequestInterceptor" />
</mvc:interceptors>
<!-- Swagger --><!--
<context:property-placeholder location="classpath:/swagger.properties" />
<bean id="springSwaggerConfig"
class="com.mangofactory.swagger.configuration.SpringSwaggerConfig" /> -->
<!-- File Upload --> <!--
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> -->
I also get GC messages like this in the console.
[GC [PSYoungGen: 605920K->128K(660480K)] 1237105K->631313K(2058752K),
0.0141920 secs] [Times: user=0.03 sys=0.00, real=0.02 secs]

How to enable logging in Spring Junit test?

How to enable logging in Spring Junit test? I think web.xml is not found when I do tests. Need to tell somehow to Junit where is web.xml with log configuration exists so logs will start working and I could bebug springs configuration errors.
My test class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("test-context.xml")
public class DSLCapacityTest {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
#Autowired private DSLCapacity dc;
private AnnotationMethodHandlerAdapter adapter;
#Before
public void setUp() throws Exception {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
response.setOutputStreamAccessAllowed(true);
adapter = new AnnotationMethodHandlerAdapter();
}
#Test
#Repeat(2)
public void testGetIndex() throws Exception {
request.setRequestURI("/dashboard/dsl-capacity/");
request.setMethod("GET");
ModelAndView mv = adapter.handle(request, response, dc);
assertSame("Incorrect message", "dashboard/dsl-capacity/index", mv.getViewName());
}
And my test-context.xml:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:amq="http://activemq.apache.org/schema/core"
xmlns:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.2.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.8.0.xsd">
<bean id="portalAuthenticator" class="uk.co.powergroup.portal.security.Authenticator">
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:ignoreUnresolvablePlaceholders="false">
<property name="location">
<value>file:/etc/portal-frontend/config.properties</value>
</property>
</bean>
<sec:authentication-manager>
<sec:authentication-provider ref='portalAuthenticator'/>
</sec:authentication-manager>
<sec:http pattern="/favicon.ico" security="none"/>
<sec:http pattern="/static/**" security="none"/>
<sec:http pattern="/logged-out" security="none"/>
<sec:http pattern="/login" security="none"/>
<sec:http pattern="/**/nologin*" security="none"/>
<sec:http auto-config="false" use-expressions="true">
<sec:csrf disabled="true"/>
<sec:intercept-url pattern="/forgot-password" access="isAnonymous()"/>
<sec:intercept-url pattern="/**" access="isAuthenticated()" />
<sec:logout logout-url="/logout" logout-success-url="/logged-out"/>
<sec:form-login login-page="/login" login-processing-url="/login-security-check" authentication-failure-url="/login" />
<sec:custom-filter position="CONCURRENT_SESSION_FILTER" ref="concurrencyFilter" />
<sec:session-management session-authentication-strategy-ref="sas"/>
<sec:custom-filter ref="userValidator" after="FILTER_SECURITY_INTERCEPTOR" />
</sec:http>
<sec:global-method-security pre-post-annotations="enabled" secured-annotations="enabled">
<sec:expression-handler ref="expressionHandler"/>
</sec:global-method-security>
<bean id="userValidator" class="uk.co.powergroup.portal.security.UserValidator">
</bean>
<bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<property name="permissionEvaluator" ref="myPermissionEvaluator"/>
</bean>
<bean id="myPermissionEvaluator" class="uk.co.powergroup.portal.security.PermissionChecker"/>
<bean id="concurrencyFilter" class="org.springframework.security.web.session.ConcurrentSessionFilter">
<constructor-arg name="sessionRegistry" ref="sessionRegistry" />
<constructor-arg name="expiredUrl" value="/login" />
</bean>
<bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/>
<bean id="sas" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy">
<constructor-arg name="sessionRegistry" ref="sessionRegistry" />
<property name="maximumSessions" value="-1"/>
</bean>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="persistenceUnitName" value="PORTAL2DB"/>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://10.10.10.249:3306/portal"/>
<property name="username" value="portal"/>
<property name="password" value="twink13s"/>
</bean>
<bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory"
destroy-method="stop">
<property name="connectionFactory">
<bean class="org.apache.activemq.spring.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>${activemq.uri}</value>
</property>
<property name="password">
<value>${activemq.password}</value>
</property>
<property name="userName">
<value>${activemq.user}</value>
</property>
</bean>
</property>
<!-- Make this 2.5 minutes in case for some reason the JMS tester job stops (sends every minute so default of 30 seconds too short) -->
<property name="idleTimeout" value="150000"/>
</bean>
<!-- Spring JMS Template -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="jmsFactory"/>
<property name="receiveTimeout" value="1000"/>
<property name="sessionTransacted" value="false"/>
</bean>
<bean id="jmsMessageListener" class="uk.co.powergroup.portal.jms.ReplyHandler"/>
<jms:listener-container container-type="default" connection-factory="jmsFactory" acknowledge="auto"
concurrency="2-5">
<jms:listener destination="${activemq.replyQueue}" ref="jmsMessageListener"/>
</jms:listener-container>
<bean id="threadPool" class="uk.co.powergroup.portal.helper.ThreadPool"/>
<bean name="retryTransactionsFilterBean" class="uk.co.powergroup.portal.helper.RetryFilter"/>
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="uk.co.powergroup.portal.converters.PermissionConverter"/>
<bean class="uk.co.powergroup.portal.converters.RoleConverter"/>
<bean class="uk.co.powergroup.portal.converters.SuiteConverter"/>
<bean class="uk.co.powergroup.portal.converters.DataCentreConverter"/>
<bean class="uk.co.powergroup.portal.converters.DataCentreLocationConverter"/>
<bean class="uk.co.powergroup.portal.converters.CompanyConverter"/>
<bean class="uk.co.powergroup.portal.converters.HardwareConverter"/>
<bean class="uk.co.powergroup.portal.converters.RackConverter"/>
<bean class="uk.co.powergroup.portal.converters.EquipmentConverter"/>
<bean class="uk.co.powergroup.portal.converters.PowerDistributionUnitTypeConverter"/>
<bean class="uk.co.powergroup.portal.converters.TimeZoneDOConverter"/>
<bean class="uk.co.powergroup.portal.converters.DslLnsBearerTypeConverter"/>
<bean class="uk.co.powergroup.portal.converters.DslLnsLocationConverter"/>
<bean class="uk.co.powergroup.portal.converters.DslLnsOrganisationConverter"/>
<bean class="uk.co.powergroup.portal.converters.DslLnsConverter"/>
<bean class="uk.co.powergroup.portal.converters.BigDecimalConverter"/>
<bean class="uk.co.powergroup.portal.converters.PstnNumberDDIConverter"/>
</set>
</property>
</bean>
<context:component-scan base-package="uk.co.powergroup.portal.dao.impl"
name-generator="uk.co.powergroup.portal.misc.BeanNameGeneratorImpl"/>
You can do configuration for log4j.properties in your test case file so it will create log for you.
#BeforeClass
public static void init() {
PropertyConfigurator.configure("src/configuration/log4j.properties");
}
Java web containers mainly used web.xml file and also web.xml file not belongs to Spring context configuration.

Spring using Anonymous Authentication Provider to use Guest User

I am using Spring framework with Security in my web application. I have a Guest user and its privileges in my db but I can't implement AnonymousAuthenticationFilter and AnonymousAuthenticationProvider to use that user. Here is my appSecurity configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<bean id="loginUrlAuthenticationEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"
p:loginFormUrl="/login" p:useForward="false" p:forceHttps="false" />
<bean id="successHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"
p:defaultTargetUrl="/" />
<bean id="failureHandler"
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
p:defaultFailureUrl="/login?error=true" p:useForward="false" />
<bean id="accessDeniedHandler"
class="com.asosyalbebe.springtest.gui.user.security.CustomAccessDeniedHandler">
<property name="accessDeniedUrl" value="/accessDenied" />
</bean>
<bean id="userDetailsService"
class="com.asosyalbebe.springtest.gui.user.service.UserServiceImpl" />
<bean id="tokenBasedRememberMeServices"
class="com.asosyalbebe.springtest.gui.user.security.CustomRememberMeServices">
<property name="alwaysRemember" value="true" />
<property name="key" value="abcdef123456" />
<property name="parameter" value="remember" />
<property name="cookieName" value="_ab_memo" />
<property name="userDetailsService" ref="userDetailsService" />
</bean>
<bean id="authenticationProcessingFilter"
class="com.asosyalbebe.springtest.gui.user.security.AuthenticationProcessingFilter">
<property name="filterProcessesUrl" value="/j_spring_security_check" />
<property name="authenticationManager" ref="authenticationManager" />
<property name="postOnly" value="true" />
<property name="authenticationSuccessHandler" ref="successHandler" />
<property name="authenticationFailureHandler" ref="failureHandler" />
<property name="rememberMeServices" ref="tokenBasedRememberMeServices" />
</bean>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider
ref="anonymousAuthProvider" />
<security:authentication-provider
ref="rememberMeAuthProvider" />
<security:authentication-provider
ref="customAuthenticationProvider" />
</security:authentication-manager>
<bean id="anonymousAuthProvider" class="com.asosyalbebe.springtest.gui.user.security.CustomAnonymousAuthProvider">
<property name="userDetailsService" ref="userDetailsService" />
<property name="key" value="foobar" />
</bean>
<bean name="rememberMeAuthProvider"
class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
<property name="key" value="xy1245aazpo98qwe" />
</bean>
<bean id="customAuthenticationProvider"
class="com.asosyalbebe.springtest.gui.user.security.UserAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService" />
</bean>
<bean id="securityContextPersistenceFilter"
class="org.springframework.security.web.context.SecurityContextPersistenceFilter">
<property name='securityContextRepository'>
<bean
class='org.springframework.security.web.context.HttpSessionSecurityContextRepository'>
<property name='allowSessionCreation' value='false' />
</bean>
</property>
</bean>
<bean id="customLogoutSuccessHandler" class="com.asosyalbebe.springtest.gui.user.security.CustomLogoutSuccessHandler" />
<bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<constructor-arg ref="customLogoutSuccessHandler" />
<constructor-arg>
<list>
<bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" />
<ref bean="tokenBasedRememberMeServices"/>
</list>
</constructor-arg>
</bean>
<bean name="rememberMeAuthenticationFilter" class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager" />
<property name="rememberMeServices" ref="tokenBasedRememberMeServices" />
</bean>
<bean id="anonymousProcessingFilter" class="org.springframework.security.web.authentication.AnonymousAuthenticationFilter">
<property name="key" value="foobar" />
<property name="userAttribute" value="anonymousUser,PRIV_ANONYMOUS" />
</bean>
<bean id="exceptionTranslationFilter" class="org.springframework.security.web.access.ExceptionTranslationFilter">
<property name="authenticationEntryPoint" ref="loginUrlAuthenticationEntryPoint" />
<property name="accessDeniedHandler" ref="accessDeniedHandler"/>
</bean>
<bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter">
<property name="rolePrefix" value="PRIV_"/>
</bean>
<bean id="accessDecisionManager" class="com.asosyalbebe.springtest.gui.user.security.CustomAccessDecisionManager">
<property name="allowIfAllAbstainDecisions" value="false" />
<property name="decisionVoters">
<list>
<ref bean="roleVoter" />
</list>
</property>
</bean>
<bean id="securityMetadataSource" class="com.asosyalbebe.springtest.gui.user.security.CustomFilterInvocationDefinitionSource"/>
<bean id="filterInvocationInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
<property name="authenticationManager" ref="authenticationManager" />
<property name="accessDecisionManager" ref="accessDecisionManager" />
<property name="securityMetadataSource" ref="securityMetadataSource" />
<property name="rejectPublicInvocations" value="false"/>
</bean>
<bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy">
<security:filter-chain-map path-type="ant">
<security:filter-chain pattern="/**"
filters="securityContextPersistenceFilter,
logoutFilter,
authenticationProcessingFilter,
rememberMeAuthenticationFilter,
anonymousProcessingFilter,
exceptionTranslationFilter,
filterInvocationInterceptor" />
</security:filter-chain-map>
</bean>
</beans>
And here is my Custom Anonymous Authentication Provider:
package com.asosyalbebe.springtest.gui.user.security;
import org.springframework.security.authentication.AnonymousAuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import com.asosyalbebe.springtest.gui.user.model.GuiUser;
import com.asosyalbebe.springtest.gui.user.service.UserService;
#SuppressWarnings("deprecation")
public class CustomAnonymousAuthProvider extends AnonymousAuthenticationProvider {
private UserService userDetailsService;
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
GuiUser user = userDetailsService.getGuestUser();
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user, "pwd", user.getAuthorities());
result.setDetails(user);
return result;
}
#Override
public boolean supports(Class<?> class1) {
return true;
}
public void setUserDetailsService(UserService userDetailsService) {
this.userDetailsService = userDetailsService;
}
}
I think the authenticate method in CustomAnonymousAuthProvider is never executed. What else can I do?
From the AuthenticationManager's perspective, the AnonymousAuthenticationToken which is created by then filter is already authenticated (the isAuthenticated property is true), so it doesn't try to authenticate it. Hence your provider is not called.
The simplest option would be to customize the AnonymousAuthenticationFilter to use the authorities from your database directly.

Spring project how do I access JBoss JNDI Datasources

Below is my current database.xml file for my Spring Project. Can someone please tell me what would have to be changed so I can use a JBoss JNDI datasource in it.. I want to do this so I don't need the config files with the database user and password and url in it.
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">
<!--
Last changed: $LastChangedDate: 2012-11-19 08:53:13 -0500 (Mon, 19 Nov 2012) $
#author $Author: johnathan.smith#uftwf.org $
#version $Revision: 829 $
-->
<context:property-placeholder location="classpath:app.properties" />
<context:component-scan base-package="org.uftwf" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<!-- these are C3P0 properties -->
<property name="acquireIncrement" value="${database.c3p0.acquireIncrement}" />
<property name="minPoolSize" value="${database.c3p0.minPoolSize}" />
<property name="maxPoolSize" value="${database.c3p0.maxPoolSize}" />
<property name="maxIdleTime" value="${database.c3p0.maxIdleTime}" />
<property name="maxIdleTimeExcessConnections" value="${database.c3p0.maxIdleTimeExcessConnections}" />
<property name="numHelperThreads" value="${database.c3p0.numHelperThreads}" />
<property name="unreturnedConnectionTimeout" value="${database.c3p0.unreturnedConnectionTimeout}" />
<property name="idleConnectionTestPeriod" value="300" />
<property name="driverClass" value="${database.driver}" />
<property name="jdbcUrl" value="${database.url}" />
<property name="user" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>org.uftwf.enrollment.model.Contact</value>
<value>org.uftwf.enrollment.model.Enrollment</value>
<value>org.uftwf.enrollment.model.Member</value>
<value>org.uftwf.enrollment.model.Profile</value>
<value>org.uftwf.enrollment.model.School</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
<prop key="format_sql">${format_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
I assume you can configure DataSource in JBoss. Notice that you have to define its JNDI name in application server configuration. Once you have the name, simply replace your dataSource bean with:
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/some-name"/>
</bean>
or shortcut:
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/some-name" expected-type="javax.sql.DataSource" />

Categories