With Spring Security I'm trying to create the following authentication verification using Spring.
#Service("LoginUserDetailsServiceImpl")
public class LoginUserDetailsServiceImpl implements UserDetailsService {
private static final Logger logger = Logger.getLogger(UserDetailsService.class);
#Autowired
private CustomerDao customerDao;
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
logger.info("Customer DAO Email:" +email);
Customer customer = customerDao.getCustomer(email);
logger.info("Customer DAO Email:" +customer.getEmail());
Roles role = customer.getRole();
logger.info("Customer DAO Role:" + role.getRoles());
MyUserPrincipalimpl principal = new MyUserPrincipalimpl(customer);
logger.info("customerUserDetails DAO:" +principal);
if (customer == null) {
throw new UsernameNotFoundException(email);
}
return principal;
}
}
Which produces the following error
5:56,638 WARN XmlWebApplicationContext:487 - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'LoginUserDetailsServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.emusicstore.dao.CustomerDao com.emusicstore.serviceImpl.LoginUserDetailsServiceImpl.customerDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.emusicstore.dao.CustomerDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
I've found if I comment out the following
<bean id="LoginUserDetailsServiceImpl" class="com.emusicstore.serviceImpl.LoginUserDetailsServiceImpl"/>
from my application-security.xml the above error is not produced. Also my junit test will execute with no issue.
#Autowired
CustomerDao customerDao;
#Test
public void LoginService() {
String email="customeremail";
logger.info("Customer DAO Email:" +email);
Customer customer = customerDao.getCustomer(email);
logger.info("Customer DAO Email:" +customer.getEmail());
Roles role = customer.getRole();
logger.info("Customer DAO Role:" + role.getRoles());
}
Repo
#Repository
public class CustomerDaoImp implements CustomerDao {
private static final Logger logger = Logger.getLogger(CustomerDaoImp.class);
#Autowired
SessionFactory sessionFactory;
Application-security.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:security="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:webflow-config="http://www.springframework.org/schema/webflow-config"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- <bean id="LoginUserDetailsServiceImpl" class="com.emusicstore.serviceImpl.LoginUserDetailsServiceImpl"/>-->
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/login_test" access="permitAll" />
<security:intercept-url pattern="/logout" access="permitAll" />
<security:intercept-url pattern="/accessdenied" access="permitAll" />
<security:intercept-url pattern="/productList" access="permitAll" />
<!-- <security:intercept-url pattern="/**" access="permitAll" /> -->
<security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
<security:intercept-url pattern="/shoppingCart/checkOut" access="hasRole('ROLE_USER')" />
<security:form-login login-page="/login_test" login-processing-url="/j_spring_security_check" authentication-failure-url="/accessdenied"
/>
<security:logout logout-success-url="/logout" />
</security:http>
<!-- <security:authentication-manager>-
<security:authentication-provider user-service-ref="LoginUserDetailsServiceImpl"/>
</security:authentication-manager> -->
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider>
<security:user-service>
<security:user name="lokesh" password="password" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mydb" />
<property name="username" value="root" />
<property name="password" value="t3l3com" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.emusicstore</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1024000" />
</bean>
</beans>
Spring-servlet.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan base-package="com.emusicstore"></context:component-scan>
<bean id="viewresolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<property name="maxUploadSize" value="10000000" />
</bean>
<mvc:resources location="/WEB-INF/resource/" mapping="/resource/**"></mvc:resources>
<tx:annotation-driven />
</beans>
I'm not sure where exactly the issue is but I'm guessing it is in how the bean is configured in the xml. Should I reference the customerDao bean when in my xml file? I would have thought the #Autowired annotation would have resolved this however?
UPDATE
If I update the application-security to add a new Customer Dao bean a new error message is thrown.
<bean id="LoginUserDetailsServiceImpl" class="com.emusicstore.serviceImpl.LoginUserDetailsServiceImpl"/>
<bean id="CustomerDao" class="com.emusicstore.daoImpl.CustomerDaoImp"/>
I get the following error 'org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.emusicstore.dao.CustomerDao] is defined: expected single matching bean but found 2: customerDaoImp,CustomerDao'
The problem is a CustomerDao instance can't be found by Spring. Either it's failed to instantiate somewhere higher up in your logs, or likely it hasn't been defined in a way that it can be instantiated and made available for injection by Spring Framework.
If you're using XML based dependency injection then defined CustomerDao instance with id customerDao in your XML similar to how LoginUserDetailsServiceImpl is defined.
Or if you're using annotation based dependency injection then add the appropriate stereotype annotation (#Component, #Repository etc) to the CustomerDao so Spring IoC knows to instantiate it and make is available for dependency injection.
Related
Im doing a new webapp with Spring and Tiles.
So far I have the login, create/edit users working.
Now I have to start with Rest Controller for third apps with json.
And I need to disable the csrf only on the rest URL's.
I tried using the XML from spring <csrf disabled="true"/> and it works but for the enthire app is there a way to do this config by path or the only way is to write it down by Java?:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
This is not working for me, every simple example I find is the same and seems to work to everyone except me, what am i doing wrong?
spring-security config:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true">
<!-- <csrf disabled="true"/> -->
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/welcome" access="hasRole('ROLE_ADMIN')"/>
<!-- <intercept-url pattern="/login" access="IS_AUTHENTICATED_ANONYMOUSLY" access="ROLE_USER,ROLE_ADMIN"/> -->
<intercept-url pattern="/administration/**" access="hasRole('ROLE_ADMIN')"/>
<form-login login-page="/login" default-target-url="/" authentication-failure-url="/login?error" username-parameter="username" password-parameter="password" />
<logout logout-success-url="/login?logout" />
</http>
<authentication-manager>
<authentication-provider ref="CustomAuthenticationProvider" />
</authentication-manager>
<beans:bean id="CustomAuthenticationProvider"
class="net.eqtconsulting.webapp.service.CustomAuthenticationProvider">
</beans:bean>
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11" />
</beans:bean>
</beans:beans>
Also my spring-mvc
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
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.0.xsd">
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/"/>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptors>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="cookieName" value="locale" />
</bean>
<!-- Application Message Bundle -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="WEB-INF/i18n/messages" />
<property name="fallbackToSystemLocale" value="false" />
<property name="useCodeAsDefaultMessage" value="true" />
<property name="cacheSeconds" value="3000" />
</bean>
<mvc:annotation-driven >
<mvc:argument-resolvers>
<bean class="org.springframework.data.web.PageableHandlerMethodArgumentResolver">
<property name="maxPageSize" value="10"></property>
</bean>
</mvc:argument-resolvers>
</mvc:annotation-driven>
<context:component-scan base-package="com.javatpoint.controller" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver" />
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
</beans>
Im also thinking about doing it by using 2 xml servlets, but how would the spring-security work, can I make it use an other one aswell?
Added this to my xml configuration and works just fine:
<http pattern="/rest/**" security="none" />
and then the other <http... </http> config for the standard app
I have seen the same question in SO but coudn't figure what's going on with my configuration.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mmm.service.ReadPropertyFilesTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mmm.singletons.VersionHandler com.mmm.service.ReadPropertyFilesTest.vHandler; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mmm.singletons.VersionHandler] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:384)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:331)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:292)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
This is the test class I use.
package com.mmm.service;
#Configurable
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {
"classpath*:spring/applicationContext.xml",
"classpath*:spring/applicationContext-jpa.xml",
"classpath*:spring/applicationContext-security.xml" })
public class ReadPropertyFilesTest {
#Autowired
private VersionHandler vHandler;
#Test
public void readPropertyFilestest() {
//VersionHandler vc = new Versi
System.out.println("open mapping \t"+vHandler.isIS_OPEN_MAPPING());
}
}
VersionHandler class
package com.mmm.singletons;
#Service
#Configurable
public class VersionHandler {
#Value(value = "${IS_OPEN_MAPPING}")
private boolean IS_OPEN_MAPPING;
public boolean isIS_OPEN_MAPPING() {
return IS_OPEN_MAPPING;
}
public void setIS_OPEN_MAPPING(boolean iS_OPEN_MAPPING) {
IS_OPEN_MAPPING = iS_OPEN_MAPPING;
}
}
applicationcontext xml file
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
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/jee
http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<context:property-placeholder location="classpath*:META-INF/spring/*.properties" />
<aop:aspectj-autoproxy />
<context:spring-configured />
<context:component-scan base-package="com.mmm">
<context:include-filter expression=".*_Roo_.*"
type="regex" />
<context:include-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Component" />
</context:component-scan>
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven mode="aspectj"
transaction-manager="transactionManager" />
<!-- Logging Aspect Bean Definition -->
<bean id="logAspect" class="com.mmm.aspect.LoggingAspect" />
<bean
class="org.springframework.transaction.aspectj.AnnotationTransactionAspect"
factory-method="aspectOf">
<property name="transactionManager" ref="transactionManager" />
</bean>
</beans>
Can somebody give me advise how to fix this?
Update
webmvc-context.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:property-placeholder location="classpath*:META-INF/spring/*.properties" />
<!-- The controllers are autodetected POJOs labeled with the #Controller
annotation. -->
<context:component-scan base-package="com.mmm.webapi.controllers"
use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
<!-- Turns on support for mapping requests to Spring MVC #Controller methods
Also registers default Formatters and Validators for use across all #Controllers -->
<mvc:annotation-driven conversion-service="applicationConversionService">
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean
class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="applicationObjectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="applicationObjectMapper" class="com.mmm.webapi.conversion.ApplicationObjectMapper" />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources -->
<mvc:resources location="/, classpath:/META-INF/web-resources/"
mapping="/resources/**" />
<!-- Allows for mapping the DispatcherServlet to "/" by forwarding static
resource requests to the container's default Servlet -->
<mvc:default-servlet-handler />
<!-- Register "global" interceptor beans to apply to all registered HandlerMappings -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor" />
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
p:paramName="lang" />
</mvc:interceptors>
<!-- Selects a static view for rendering without the need for an explicit
controller -->
<mvc:view-controller path="/" view-name="index" />
<mvc:view-controller path="/uncaughtException" />
<mvc:view-controller path="/resourceNotFound" />
<mvc:view-controller path="/dataAccessFailure" />
<!-- Resolves localized messages*.properties and application.properties
files in the application to allow for internationalization. The messages*.properties
files translate Roo generated messages which are part of the admin interface,
the application.properties resource bundle localizes all application specific
messages such as entity names and menu items. -->
<bean
class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
id="messageSource" p:basenames="WEB-INF/i18n/messages,WEB-INF/i18n/application"
p:fallbackToSystemLocale="false" />
<!-- Store preferred language configuration in a cookie -->
<bean class="org.springframework.web.servlet.i18n.CookieLocaleResolver"
id="localeResolver" p:cookieName="locale" />
<!-- Resolves localized <theme_name>.properties files in the classpath to
allow for theme support -->
<bean
class="org.springframework.ui.context.support.ResourceBundleThemeSource"
id="themeSource" />
<!-- Store preferred theme configuration in a cookie -->
<bean class="org.springframework.web.servlet.theme.CookieThemeResolver"
id="themeResolver" p:cookieName="theme" p:defaultThemeName="standard" />
<!-- This bean resolves specific types of exceptions to corresponding logical
- view names for error views. The default behaviour of DispatcherServlet
- is to propagate all exceptions to the servlet container: this will happen
- here with all other types of exceptions. -->
<!-- <bean -->
<!-- class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" -->
<!-- p:defaultErrorView="uncaughtException"> -->
<!-- <property name="exceptionMappings"> -->
<!-- <props> -->
<!-- <prop key=".DataAccessException">dataAccessFailure</prop> -->
<!-- <prop key=".NoSuchRequestHandlingMethodException">resourceNotFound</prop> -->
<!-- <prop key=".TypeMismatchException">resourceNotFound</prop> -->
<!-- <prop key=".MissingServletRequestParameterException">resourceNotFound</prop> -->
<!-- </props> -->
<!-- </property> -->
<!-- </bean> -->
<!-- Enable this for integration of file upload functionality -->
<bean
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
id="multipartResolver" />
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver"
id="tilesViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>
<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"
id="tilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/layouts/layouts.xml</value>
<!-- Scan views directory for Tiles configurations -->
<value>/WEB-INF/views/**/views.xml</value>
</list>
</property>
</bean>
<bean
class="com.mmm.webapi.conversion.ApplicationConversionServiceFactoryBean"
id="applicationConversionService" />
<!-- <bean class="com.mangofactory.swagger.configuration.SpringSwaggerConfig"
/>
-->
<bean class="com.mmm.webapi.documentation.SwaggerConfig" />
</beans>
I am using Spring Security and using Pre-Authentication module as my application is authenticated using Siteminder.
Following is the spring config XML
<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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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.1.xsd">
<!-- http403EntryPoint -->
<security:http use-expressions="true" auto-config="false" entry-point-ref="http403EntryPoint">
<!-- Additional http configuration omitted -->
<security:intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
<security:custom-filter position="PRE_AUTH_FILTER" ref="siteminderFilter" />
</security:http>
<bean id="siteminderFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
<property name="principalRequestHeader" value="SM_USER"/>
<property name="authenticationManager" ref="authenticationManager" />
</bean>
<bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<property name="preAuthenticatedUserDetailsService">
<bean id="userDetailsServiceWrapper" class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<property name="userDetailsService" ref="customUserDetailsService"/>
</bean>
</property>
</bean>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="preauthAuthProvider" />
</security:authentication-manager>
<bean id="customUserDetailsService" class="com.vzw.iaas.security.service.CustomUserDetailsService"></bean>
<bean id="http403EntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"></bean>
<bean id="exceptionTranslationFilter"
class="org.springframework.security.web.access.ExceptionTranslationFilter">
<property name="authenticationEntryPoint" ref="authenticationEntryPoint"/>
<property name="accessDeniedHandler" ref="accessDeniedHandler"/>
</bean>
<bean id="authenticationEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<property name="loginFormUrl" value="/NotAuthorized.html"/>
</bean>
<bean id="accessDeniedHandler"
class="org.springframework.security.web.access.AccessDeniedHandlerImpl">
<property name="errorPage" value="/accessDenied.html"/>
</bean>
Now when there is an exception i.e. when I am sending a request to the application without sending a SM_USER the appliaction instead of showing the error page i.e. in that case NotAuthorized.html throws and internal server 500 error.
I would like to show my custom error pages in following scenarios.
1. When there is an AuthenticationException
2. When the user has no access.
Can Spring Security masters tell me what I am missing here.
Make the exceptionIfHeaderMissing flag as false. Instead of throwing the error, the request will be handled using http403EntryPoint.
<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>
Getting error when adding Transaction-Manager. What's wrong? :/
Few possible answers reffer to lack of some hibernate libraries. However It seems that all of them do persist. How to overcome this?
Also I want to add some test data to my database. In what class is it better to insert it?
Thank you.
ERROR:
org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception
parsing XML document from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]; nested
exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
Dispatcher-Servlet:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="miniVLE.controller" />
<context:component-scan base-package="miniVLE.service" />
<context:component-scan base-package="miniVLE.beans" />
<context:component-scan base-package="miniVLE.dao" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<!-- Declare a view resolver-->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!-- Connects to the database based on the jdbc properties information-->
<bean id="dataSource" class ="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name ="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name ="url" value="jdbc:derby://localhost:1527/minivledb"/>
<property name ="username" value="root"/>
<property name ="password" value="123" />
</bean>
<!-- Declares hibernate object -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<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>
</props>
</property>
<!-- A list of all the annotated bean files, which are mapped with database tables-->
<property name="annotatedClasses">
<list>
<value> miniVLE.beans.Course </value>
<value> miniVLE.beans.Student </value>
<value> miniVLE.beans.Department </value>
<value> miniVLE.beans.Module </value>
<value> miniVLE.beans.TimeSlot </value>
</list>
</property>
</bean>
<!-- Declare a transaction manager-->
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
DAO:
#Repository
public class MiniVLEDAOImplementation implements MiniVLEDAO{
// Used for communicating with the database
#Autowired
private SessionFactory sessionFactory;
#Override
public void addStudentToDB(Student student) {
sessionFactory.getCurrentSession().saveOrUpdate(student);
}....
Service:
#Service
#Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class StudentService implements IStudentService{
#Autowired
MiniVLEDAOImplementation dao;
public StudentService() {
System.out.println("*** StudentService instantiated");
}
#Override
public Student getStudent(String urn){
Student s = dao.getStudentFromDB(urn);
return s;
}
#Override
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addStudent(Student student) {
dao.addStudentToDB(student);
}...
Controller:
#Controller
public class miniVLEController {
#Autowired
StudentService studentService;
After adding the aopalliance-1.0.jar getting next
ERROR:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'miniVLEController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: miniVLE.service.StudentService miniVLE.controller.miniVLEController.studentService; nested exception is java.lang.IllegalArgumentException: Can not set miniVLE.service.StudentService field miniVLE.controller.miniVLEController.studentService to sun.proxy.$Proxy536
One of the solutions was to add <aop:aspectj-autoproxy proxy-target-class="true"/>into the dispatcher-servlet.
next Error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'miniVLEController' defined in file
[C:\Users\1\Documents\NetBeansProjects\com3014_mini_VLE\build\web\WEB-
INF\classes\miniVLE\controller\miniVLEController.class]: BeanPostProcessor before
instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError:
org/aspectj/lang/annotation/Aspect
You need to add aopalliance.jar dependency.
If you use maven:
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
Following the problem escalation:
Needed to find aspectjrt-1.x.x.jar that was missing to overcome last error and then to overcome org.aspectj.util.PartialOrder.PartialComparable error you need to get aspectjtools-1.X.X.jar
here I found all extra libraries i needed
http://www.jarfinder.com/index.php/java/info/org.aspectj.lang.NoAspectBoundException
I am trying to setup my Spring CAS.XML file but I dont know why the file is not seeing the values I have set in the file:
Can someone please tell me what I am getting the following error:
2012-09-10 11:16:00,396 ERROR org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'requestSingleLogoutFilter' defined in ServletContext resource [/WEB-INF/spring/CAS-Local.xml]: Could not resolve placeholder 'cas.server.host'
at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:209)
if you look I do have the values setup at the end of the file...
Here is my CAS-Local.xml file:
<?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"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<security:http entry-point-ref="casEntryPoint"
use-expressions="true">
<security:intercept-url pattern="/" access="permitAll" />
<security:intercept-url pattern="/index.jsp"
access="permitAll" />
<security:intercept-url pattern="/cas-logout.jsp"
access="permitAll" />
<security:intercept-url pattern="/casfailed.jsp"
access="permitAll" />
<security:intercept-url access="hasRole('ROLE_MEMBER_INQUIRY')"
pattern="/visit**" />
<security:custom-filter ref="requestSingleLogoutFilter"
before="LOGOUT_FILTER" />
<security:custom-filter ref="singleLogoutFilter"
before="CAS_FILTER" />
<security:custom-filter ref="casFilter"
position="CAS_FILTER" />
<security:logout logout-success-url="/cas-logout.jsp" />
</security:http>
<security:authentication-manager alias="authManager">
<security:authentication-provider
ref="casAuthProvider" />
</security:authentication-manager>
<security:ldap-server id="ldapServer"
url="ldaps://dvldap01.uftwf.dev:636/dc=uftwf,dc=dev" manager-dn="cn=xxx,dc=uftwf,dc=dev"
manager-password="xxx" />
<security:ldap-user-service id="userServiceLDAP"
server-ref="ldapServer" user-search-base="ou=webusers"
user-search-filter="(uid={0})" group-search-base="ou=groups"
group-role-attribute="cn" group-search-filter="(uniqueMember={0})"
role-prefix="ROLE_" />
<!-- This filter handles a Single Logout Request from the CAS Server -->
<bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter" />
<!-- This filter redirects to the CAS Server to signal Single Logout should
be performed -->
<bean id="requestSingleLogoutFilter"
class="org.springframework.security.web.authentication.logout.LogoutFilter"
p:filterProcessesUrl="/j_spring_cas_security_logout">
<constructor-arg
value="https://${cas.server.host}/cas-server-webapp/logout" />
<constructor-arg>
<bean
class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" />
</constructor-arg>
</bean>
<bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties"
p:service="http://wcmisdlin07.uftmasterad.org:8080/SchoolVisitLocked/j_spring_cas_security_check"
p:authenticateAllArtifacts="true" />
<bean id="casEntryPoint"
class="org.springframework.security.cas.web.CasAuthenticationEntryPoint"
p:serviceProperties-ref="serviceProperties"
p:loginUrl="https://6dvews01.uftwf.dev:8443/cas-server-webapp/login" />
<bean id="casFilter"
class="org.springframework.security.cas.web.CasAuthenticationFilter"
p:authenticationManager-ref="authManager" p:serviceProperties-ref="serviceProperties"
p:proxyGrantingTicketStorage-ref="pgtStorage"
p:proxyReceptorUrl="/j_spring_cas_security_proxyreceptor">
<property name="authenticationDetailsSource">
<bean
class="org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource" />
</property>
<property name="authenticationFailureHandler">
<bean
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
p:defaultFailureUrl="/casfailed.jsp" />
</property>
<property name="authenticationSuccessHandler">
<bean
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"
p:defaultTargetUrl="/visit" />
</property>
</bean>
<!-- NOTE: In a real application you should not use an in memory implementation.
You will also want to ensure to clean up expired tickets by calling ProxyGrantingTicketStorage.cleanup() -->
<bean id="pgtStorage"
class="org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl" />
<bean id="casAuthProvider"
class="org.springframework.security.cas.authentication.CasAuthenticationProvider"
p:serviceProperties-ref="serviceProperties" p:key="casAuthProviderKey">
<property name="authenticationUserDetailsService">
<bean
class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<constructor-arg ref="userServiceLDAP" />
</bean>
</property>
<property name="ticketValidator">
<bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
<constructor-arg index="0"
value="https://6dvews01.uftwf.dev:8443/cas-server-webapp" />
</bean>
</property>
</bean>
<!-- Configuration for the environment can be overriden by system properties -->
<context:property-placeholder
system-properties-mode="OVERRIDE" properties-ref="environment" />
<util:properties id="environment">
<prop key="cas.service.host">wcmisdlin07.uftmasterad.org:8443</prop>
<prop key="cas.server.host">6dvews01.uftwf.dev:8443</prop>
</util:properties>
</beans>
you use placeholders for properties like "${cas.server.host}" which must be defined in a property file and resolved by spring. create a new property file "your.properties" in your classpath and add this into your context:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>your.properties</value>
</property>
</bean>
your.properties:
cas.server.host=http://localhost/abc