I have a SpringMVC project (working). I decided that I want test spring-security library and I get it to my project. Now, I am getting this error:
INFORMACIÓN: Starting Servlet Engine: Apache Tomcat/8.0.36
jul 27, 2017 7:17:31 PM org.apache.jasper.servlet.TldScanner scanJars
INFORMACIÓN: Al menos un JAR, que se ha explorado buscando TLDs, aún no contenía TLDs. Activar historial de depuración para este historiador para una completa lista de los JARs que fueron explorados y de los que nos se halló TLDs. Saltarse JARs no necesarios durante la exploración puede dar lugar a una mejora de tiempo significativa en el arranque y compilación de JSP .
jul 27, 2017 7:17:31 PM org.apache.catalina.core.ApplicationContext log
INFORMACIÓN: 1 Spring WebApplicationInitializers detected on classpath
jul 27, 2017 7:17:31 PM org.apache.catalina.core.ApplicationContext log
INFORMACIÓN: Initializing Spring root WebApplicationContext
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Thu Jul 27 19:17:31 CEST 2017]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/root-context.xml]
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 255 ms
jul 27, 2017 7:17:32 PM org.apache.catalina.core.StandardContext filterStart
GRAVE: Excepción arrancando filtro springSecurityFilterChain
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1084)
I tried fix it adding this to my web.xml file (of my spring-mvc project) but then tomcats crash in fatal error (without detail), works fine again when I removed this code:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
My security config is this:
SecurityConfig.java (My spring-security class)
package com.myproject.security;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
#Qualifier("dataSource")
DataSource dataSource;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.authorizeRequests()
.antMatchers("/", "/register", "/login").access("hasRole('DEFAULT')")
.antMatchers("/web").access("hasRole('USER')")
.antMatchers("/admin").access("hasRole('ADMIN')")
.anyRequest().permitAll()
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout()
.logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.csrf()
.and()
.cors();
// #formatter:on
}
}
CustomUserDetailService.java My user-roles service (for spring-security use)
package com.everyhuman.security;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.myproject.web.register.service.ServiceUser;
import com.myproject.web.users.dto.DTORoles;
import com.myproject.web.users.dto.DTOUser;
#Service("customUserDetailService")
public class CustomUserDetailService implements UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailService.class);
#Autowired
private ServiceUser serviceUser;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
DTOUser user = serviceUser.findUserByUsername(username);
if (user == null) {
logger.info("User not found");
throw new UsernameNotFoundException("Username not found");
}
/*
* Devolvemos un usuario securizado por spring
*/
return new User(user.getUsername(), user.getPassword(), getGrantedAuthorities(user));
}
/**
* Obtiene los roles del usuario
*
* #param user
* #return
*/
private List<GrantedAuthority> getGrantedAuthorities(DTOUser user) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (DTORoles userProfile : user.getRoles()) {
authorities.add(new SimpleGrantedAuthority(userProfile.toString()));
}
return authorities;
}
}
SecurityWebApplicationInitializer.java (This class is for initialize Spring-Security)
package com.myproject.security;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
This my spring config:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
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.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.myproject">
<context:include-filter type="regex" expression="com.myproject.*.controller.*"/>
</context:component-scan>
<context:property-placeholder location="classpath:ehconf/*.properties" />
<beans:bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="packagesToScan" value = "com.myproject.web" />
<beans:property name="jpaVendorAdapter">
<beans:bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</beans:property>
<beans:property name="jpaProperties">
<beans:props>
<beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/ehdatabase?serverTimezone=UTC" />
<beans:property name="username" value="ehdatabase" />
<beans:property name="password" value="ehdatabase123" />
</beans:bean>
<beans:bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="myEmf" />
</beans:bean>
<tx:annotation-driven />
<beans:bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans:beans>
And this my web.xml config:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml
<!-- /WEB-INF/spring/spring-security.xml -->
</param-value>
</context-param>
<!-- <filter> -->
<!-- <filter-name>springSecurityFilterChain</filter-name> -->
<!-- <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> -->
<!-- </filter> -->
<!-- <filter-mapping> -->
<!-- <filter-name>springSecurityFilterChain</filter-name> -->
<!-- <url-pattern>/*</url-pattern> -->
<!-- </filter-mapping> -->
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I recommend that you stick to Java Config since you are using Tomcat 8
Note that the XML security part is not required if you have
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
So you can just delete
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Then, make sure that the package, which contains the secuirty configuration is added to the component scan
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.myproject.security")
public class HelloWorldConfiguration {
#Bean
public ViewResolver viewResolver() {
//InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
//viewResolver.setViewClass(JstlView.class);
//viewResolver.setPrefix("/WEB-INF/views/");
//viewResolver.setSuffix(".jsp");
// Set View Resolver
return viewResolver;
}
}
You can also delete the web.xml and use this instead
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { HelloWorldConfiguration.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
For the complete example check http://websystique.com/spring-security/spring-security-4-hello-world-annotation-xml-example/
For JPA Config you can add something like this
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = { "com.myproject.repository" })
public class PersistenceJPAConfig {
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.myproject.jpa.entites"});
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
private DatabasePopulator createDatabasePopulator() {
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.setContinueOnError(true);
databasePopulator.addScript(new ClassPathResource("dropdownlist.sql"));
// databasePopulator.addScript(new ClassPathResource("persistentlogins.sql"));
// databasePopulator.addScript(new ClassPathResource("countries.sql"));
// databasePopulator.addScript(new ClassPathResource("states.sql"));
// databasePopulator.addScript(new ClassPathResource("cities.sql"));
return databasePopulator;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
// dataSource.setDriverClassName("com.mysql.jdbc.Driver");
// dataSource.setUrl("jdbc:mysql://localhost:3306/spring_jpa");
// dataSource.setUsername("tutorialuser");
// dataSource.setPassword("tutorialmy5ql");
dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
dataSource.setUrl("jdbc:sqlserver://localhost\\SQLEXPRESS;databaseName=ContractTracker");
dataSource.setUsername("ctReader");
dataSource.setPassword("ctreader");
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
DatabasePopulatorUtils.execute(createDatabasePopulator(), dataSource());
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
return properties;
}
}
EDITED: Have you tried to add the bean deffinition?
<bean id="springSecurityFilterChain" class="org.springframework.web.filter.DelegatingFilterProxy"/>
Another possible fail is that I can't see in your config the listener that starts the spring context:
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
Check the Spring page for more information.
OLD: I can't add a comment due to low reputation, so can you post your web.xml and your security.xml please?
Related
UPDATE
Adding code in GameDetailImageMapper
package spring;
import entities.GameDetailImage;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class GameDetailImageMapper implements RowMapper
{
public GameDetailImage mapRow(ResultSet rs,int rowNum) throws SQLException
{
GameDetailImage gDetailImage = new GameDetailImage();
System.out.println("++++++++++++"+rs.toString());
gDetailImage.getGameDetail().setGameid( rs.getInt("game_id"));
gDetailImage.getGameDetail().setTitle( rs.getString("title"));
gDetailImage.getGameDetail().setDeveloper( rs.getString("developer"));
gDetailImage.getGameDetail().setPublisher( rs.getString("publisher"));
gDetailImage.getGameDetail().setGenre( rs.getString("genre"));
gDetailImage.getGameDetail().setPlatform( rs.getString("platform"));
gDetailImage.getGameDetail().setGameDescription( rs.getString("game_description"));
gDetailImage.getGameDetail().setDistribution( rs.getString("distribution"));
gDetailImage.getGameDetail().setReleaseDate( rs.getDate("release_date"));
gDetailImage.getGameDetail().setCreateDate( rs.getDate("create_date"));
gDetailImage.getGameDetail().setScore( rs.getInt("score"));
gDetailImage.getGameImage().setBanner_link( rs.getString("banner_link"));
gDetailImage.getGameImage().setBanner_title( rs.getString("banner_title"));
gDetailImage.getGameImage().setHero_link( rs.getString("hero_link"));
gDetailImage.getGameImage().setHero_title( rs.getString("hero_title"));
gDetailImage.getGameImage().setThumbnail_link( rs.getString("thumbnail_link"));
gDetailImage.getGameImage().setThumbnail_title( rs.getString("thumbnail_title"));
gDetailImage.getGameImage().setContent_image_link( rs.getString("content_image_link"));
gDetailImage.getGameImage().setContent_image_title( rs.getString("content_image_title"));
return gDetailImage;
}
}
Now that I have pointed my context config to the data.xml file I am getting the below exception. Not sure why this is happening as the query returns the correct data from my database. I am using a composite object in my mapper (two objects are included in the composite). Could that be what is causing the issue?
Stacktrace:] with root cause
java.lang.NullPointerException
at spring.GameDetailImageMapper.mapRow(GameDetailImageMapper.java:23)
at spring.GameDetailImageMapper.mapRow(GameDetailImageMapper.java:17)
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:93)
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60)
at org.springframework.jdbc.core.JdbcTemplate$1QueryStatementCallback.doInStatement(JdbcTemplate.java:455)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:400)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:466)
I am getting the following exception for my simple spring application. Think because I am not using spring injection correctly for the jdbcTemplate. I am using spring without Maven so no pom.xml. Running on Tomcat.
Could not autowire field: private org.springframework.jdbc.core.JdbcTemplate spring.GameDetailImageManagement.jdbcTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] 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)}
web.xml:
<?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">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
data.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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/GameDisplay" />
<property name="username" value= />
<property name="password" value= />
<property name="initialSize" value="2" />
<property name="maxActive" value="5" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg type="javax.sql.DataSource" name="dataSource" ref="dataSource"/>
</bean>
<context:annotation-config />
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<!--Handle #Autowired-->
<context:annotation-config />
</beans>
`GameDetailImageController:
package controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.beans.factory.annotation.Autowired;
import spring.GameDetailImageManagement;
#Controller
public class GameDetailImageController
{
#Autowired
private GameDetailImageManagement gdm;
#RequestMapping("/index")
protected ModelAndView listGameDetailImages
(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mv = new ModelAndView("index");
//ModelAndView mv = new ModelAndView("index", "gameDetailImages", dao.GameDetailImageDAO.getGameDetailImages());
mv.addObject("gameDetailImages", gdm.getGameDetailImages());
return mv;
}
}
GameDetailImageManagement
package spring;
import entities.GameDetailImage;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class GameDetailImageManagement
{
#Autowired
private JdbcTemplate jdbcTemplate;
#Autowired
public void setDataSource(DataSource dataSource)
{
this.jdbcTemplate.setDataSource(dataSource);
}
/*public void setJdbcTemplate(JdbcTemplate template)
{
this.jdbcTemplate = template;
}*/
public List getGameDetailImages()
{
//List templist;
//templist = jdbcTemplate.query("select * from GameDetail Inner Join GameImage on GameDetail.game_id = GameImage.game_id Order By GameDetail.create_date", new GameDetailImageMapper());
//System.out.println("++++===++++"+templist.toString());
return this.jdbcTemplate.query("select * from GameDetail Inner Join GameImage on GameDetail.game_id = GameImage.game_id Order By GameDetail.create_date", new GameDetailImageMapper());
}
}
Thanks pointing the config file to my data.xml was the first step. The next step was that I wasn't using the mapper correctly. I added the getters and setters directly to the GameDetailImageMapper without using getGameDetail() and getGameImage().
I am new to spring security and trying to perform login using spring security but when i clink login button in login page, it shows 404 error.
I am using angular js for frontend.
My login action is /user/login which i am calling from login_service.js.
Below is spring configuration files.
web.xml
---------
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>CCUAPP</display-name>
<description>Credit Card Application</description>
<!-- For web context -->
<servlet>
<servlet-name>ccuapp-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ccuapp-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- For root context -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-core-config.xml</param-value>
</context-param>
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
spring-mvc-config.xml
=====================
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd ">
<!-- **************************************************************** -->
<!-- SPRING ANNOTATION PROCESSING -->
<!-- **************************************************************** -->
<mvc:annotation-driven />
<context:component-scan base-package="com.nfdil.ccuapp.web" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/static/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>/WEB-INF/LableResources</value>
<value>/WEB-INF/MessageResources</value>
</list>
</property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
<!-- **************************************************************** -->
<!-- RESOURCE FOLDERS CONFIGURATION -->
<!-- Dispatcher configuration for serving static resources -->
<!-- **************************************************************** -->
<mvc:resources location="/static/" mapping="/static/**" />
</beans>
SecurityConfiguration.java
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
private static String REALM="MY_TEST_REALM";
public static final String UserListURL = "/getAllCompanies";
public static final String loginURL = "/user/login";
public static final String logoutURL = "/logout";
public static final String getUploadTransURL = "/getAllTransactions";
#Autowired
private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
#Autowired
TokenBasedAuthenticationService tokenBasedAuthenticationService;
#Autowired
SuccessHandler successHandler;
#Autowired
FailureHandler failureHandler;
#Autowired
CustomAuthenticationProvider customAuthenticationProvider;
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationProvider);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and()
.formLogin()
.loginProcessingUrl(loginURL)
.usernameParameter("username")
.passwordParameter("password")
.successHandler(successHandler)
.failureHandler(failureHandler)
.failureUrl(logoutURL)
.permitAll()
.and()
.authorizeRequests()
.filterSecurityInterceptorOncePerRequest(true)
.antMatchers(UserListURL).access("hasRole('ROLE_ADMIN')")
.antMatchers(getUploadTransURL).permitAll()
.and()
.csrf()
.disable()
.addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class)
.addFilterBefore(getCustomAuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterAfter(new CustomAuthenticationFilter(tokenBasedAuthenticationService),UsernamePasswordAuthenticationFilter.class);
super.configure(http);
}
#Bean
public CustomAuthenticationProcessingFilter getCustomAuthenticationProcessingFilter() throws Exception{
CustomAuthenticationProcessingFilter customAuthenticationProcessingFilter = new CustomAuthenticationProcessingFilter(loginURL);
customAuthenticationProcessingFilter.setAuthenticationManager(authenticationManager());
customAuthenticationProcessingFilter.setAuthenticationSuccessHandler(successHandler);
customAuthenticationProcessingFilter.setAuthenticationFailureHandler(failureHandler);
return customAuthenticationProcessingFilter;
}
}
login_service.js
'use strict';
angular.module('myApp').factory('LoginService', ['$http', '$q', function($http, $q){
var factory = {
login:login
};
return factory;
function login(user) {
var uploadUrl = "user/login";
var deferred = $q.defer();
$http.post(uploadUrl, {params:{username:user.userid,password:user.password}},{ headers : {
'Content-Type': 'application/x-www-form-urlencoded'
}})
.then(
function (response) {
deferred.resolve(response);
},
function(errResponse){
console.info(' login submit'+errResponse);
deferred.reject(errResponse);
}
);
return deferred.promise;
}
}]);
Please help what i am missing.
I am trying to implement a spring security in my project my requirements are
First user will login with url that will generate a secuirty code -
http://localhost:8181/SpringSecurity/login
After successfully loggedIn I hit secuired API call like -
http://localhost:8181/SpringSecurity/admin with secured key generated by login method
I am using crome postman to hit APIs
Although I am loggedIn with a user having ROLE_ADMIN but still it is not allow me to access secured APIs
my web.xml is
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
servlet-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:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<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/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.ha.**"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="savedRequestAwareAuthenticationSuccessHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="targetUrlParameter" value="targetUrl" />
</bean>
<context:component-scan base-package="com.ha.**" />
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="prefixJson" value="false" />
<property name="supportedMediaTypes" value="application/json" />
</bean>
<import resource="../spring-security.xml"/>
spring-security.xml
<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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
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-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<security:global-method-security secured-annotations="enabled"/>
<http auto-config="true">
<intercept-url pattern="/admin**" access="ROLE_ADMIN" />
<custom-filter ref="tokenProcessingFilter" after="FORM_LOGIN_FILTER" />
</http>
<beans:bean
class="com.ha.security.AuthenticationTokenAndSessionProcessingFilter"
id="tokenProcessingFilter">
<beans:constructor-arg name="principal" value="ANONYMOUS" />
<beans:constructor-arg name="authority" value="anonymousUser" />
<beans:constructor-arg name="tokenStore" ref="inMemoryTokenStore" />
</beans:bean>
<beans:bean class="com.ha.security.InMemoryTokenStore" id="inMemoryTokenStore" />
<authentication-manager>
<authentication-provider>
<user-service>
<user name="hr" password="123456" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
Controller file is
package com.ha.security;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ha.model.UserEntity;
import com.ha.services.IUserService;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
#Autowired
private InMemoryTokenStore tokenStore;
#Autowired
IUserService userServices;
/* #RequestMapping(value = { "/" }, method = RequestMethod.GET)
public String welcomePage() {
return "index";
} */
#RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
#Secured("ROLE_ADMIN")
public #ResponseBody String defaultPage() {
List<UserEntity> userEntity = userServices.getUsersList();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.toJson(userEntity);
}
#RequestMapping(value = "/admin", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody
public ResponseDto adminPage() {
return new ResponseDto("Can Access Admin");
}
#RequestMapping(value = "/login", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody
public ResponseDto login(#RequestBody UserLoginDto loginDto) {
String userName = loginDto.getUserName();
String password = loginDto.getPassword();
if (StringUtils.hasText(userName) && StringUtils.hasText(password)
&& userServices.validateAdminUser(loginDto)) {
ArrayList<GrantedAuthority> objAuthorities = new ArrayList<GrantedAuthority>();
SimpleGrantedAuthority objAuthority = new SimpleGrantedAuthority(
"ROLE_ADMIN");
objAuthorities.add(objAuthority);
User user = new User(userName, password, objAuthorities);
return new ResponseDto(this.tokenStore.generateAccessToken(user));
} else {
return new ResponseDto("Not Valid User");
}
}
}
AuthenticationTokenAndSessionProcessingFilter
package com.ha.security;
import java.io.IOException;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
public class AuthenticationTokenAndSessionProcessingFilter extends
GenericFilterBean {
private final InMemoryTokenStore tokenStore;
private final Object principal;
private final List<GrantedAuthority> authorities;
public AuthenticationTokenAndSessionProcessingFilter(
InMemoryTokenStore tokenStore, String authority, String principal) {
this.tokenStore = tokenStore;
this.principal = principal;
this.authorities = AuthorityUtils.createAuthorityList(authority);
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
throw new RuntimeException("Expecting a HTTP request");
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
String authToken = null;
UserDetails objUserDetails = null;
if (StringUtils.hasText(httpRequest.getHeader("Authorization"))) {
authToken = httpRequest.getHeader("Authorization");
objUserDetails = this.tokenStore
.readAccessToken(authToken);
}
setAuthentication(objUserDetails, httpRequest);
chain.doFilter(request, response);
}
private void setAuthentication(UserDetails objUserDetails,
HttpServletRequest request) {
UsernamePasswordAuthenticationToken authentication = null;
if (null != objUserDetails) {
authentication = new UsernamePasswordAuthenticationToken(
objUserDetails, null, objUserDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource()
.buildDetails(request));
SecurityContextHolder.getContext()
.setAuthentication(authentication);
} else {
authentication = new UsernamePasswordAuthenticationToken(
this.principal, null, this.authorities);
SecurityContextHolder.getContext()
.setAuthentication(authentication);
}
}
}
I believe you need to use hasRole method
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
And also I noticed that you have only one user in your users list with role "ROLE_USER" hope you have added the admin user as well.
Thanks for your support, Problem get solved now and It was with importing style of security action. I was importing securty xml file multiple times
I had import securty in
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/spring-security.xml
</param-value>
</context-param>
as well as in spring-context.xml file
<import resource="../spring-security.xml"/>
due to that multiple instances creted of inMemoryTokenStore and while validating it checking user token with different one.
After removed entry from spring-context.xml and adding following qualifer in HomeController my code is working fine
#Qualifier("inMemoryTokenStore")
private InMemoryTokenStore tokenStore;
Thanks evertybuddy....:)
I am developing a primefaces - spring framework application but i have a big problem with my beans
i'm using spring annotations in java code to discover my beans, services, or component
but the problem is when i start jboss 7.1 AS and the beans are created i can see that my bean ListUsersBean
is created succesfully and the autowired setters are set successfully, but after when i try to invoke a test() method
from jsf page the autowired attributes are null.
I dont know what is happening
thanks a lot if anyone may help me
i'm using
spring-framework 3.2.2
JBOSS AS 7.1
primefaces 3.5
this is my bean
package edu.unbosque.beans;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ManagedProperty;
import edu.unbosque.model.User;
import edu.unbosque.services.IUserService;
import edu.unbosque.services.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
#Component
#ManagedBean
#SessionScoped
public class ListUsersBean implements Serializable{
/**
* Acceso A Datos De Usuario
*/
private IUserService userService;
private TestService testService;
/**
* Listado De Usuarios
*/
private List<User> usersList;
/**
* Usuario Seleccionado
*/
private User selectedUser;
/**
* Carga Los Usuarios
*/
private void populateUsers(){
this.usersList = this.userService.getUsers();
}
public IUserService getUserService() {
return userService;
}
#Autowired(required = true)
#Qualifier("userServiceImpl")
public void setUserService(IUserService userService) {
this.userService = userService;
}
public List<User> getUsersList() {
return usersList;
}
public void setUsersList(List<User> usersList) {
this.usersList = usersList;
}
public User getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(User selectedUser) {
this.selectedUser = selectedUser;
}
public TestService getTestService() {
return testService;
}
#Autowired
public void setTestService(TestService testService) {
this.testService = testService;
}
public void test(){
this.testService = this.getTestService();
int i = 1;
i = i + 2;
}
}
this is my service
package edu.unbosque.services;
import java.util.List;
import javax.faces.bean.ManagedProperty;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import edu.unbosque.*;
import edu.unbosque.dao.UserDao;
import edu.unbosque.model.User;
import javax.inject.Named;
#Named("userServiceImpl")
public class UserServiceImpl implements IUserService{
#Autowired
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return (UserDetails) userDao.getUserByUserName(username);
}
#Override
public List<User> getUsers() {
return getUserDao().getUsers();
}
}
config files
faces-config.xml
*
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
<lifecycle>
<phase-listener>edu.unbosque.listeners.LoginPhaseListener</phase-listener>
</lifecycle>
</faces-config>
*
spring-database.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:annotation-config />
<context:component-scan base-package="edu.unbosque.model" />
<context:component-scan base-package="edu.unbosque.dao" />
<context:component-scan base-package="edu.unbosque.services" />
<context:component-scan base-package="edu.unbosque.beans" />
<context:property-placeholder location="classpath:jdbc.properties" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" 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>edu.unbosque.model.User</value>
<value>edu.unbosque.model.Authority</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.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>
web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml,
/WEB-INF/spring-database.xml
</param-value>
</context-param>
<display-name>Semilleros Universidad El Bosque</display-name>
<!-- Change to "Production" when you are ready to deploy -->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- Welcome page -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- JSF mapping -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map these files with JSF -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>bootstrap</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
</web-app>
The problem is you are mixing up jsf, CDI and spring annotations. Use #Component in your class UserServiceImpl. Because if you use #Named, the created bean's life cycle will be managed by CDI, because its a CDi annotation. So as you are using #Autowired annotation to inject the bean, which is unknown to Spring, will get null. So as you are using #Autowired while injecting the bean, the injecting bean must be in spring managed context and to do that you should have use #Component. For further reading you can see this nice tutorial.
Is spring security 3.1.3 have an issue #Autowired not work when using WebApplicationInitializer?
I get NullPointerException
SEVERE: java.lang.NullPointerException
at com.x.y.service.impl.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:29)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:101)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:132)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:195)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
UserDetailsServiceImpl
package com.x.y.service.impl;
import com.x.y.dao.UserDao;
import com.x.y.dto.User;
import com.x.y.util.Assembler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
#Component
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired UserDao userDao;
#Autowired Assembler assembler;
#Override
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) {
try{
User user = userDao.findByUserName(username);
if(user == null) {
System.out.println("[Login] username: " + username + " not found! back to login page");
//throw new UsernameNotFoundException("[Login] User : " + username + " not found!");
} else {
System.out.println("[Login] username: " + username + " found! try to assemble user");
}
return assembler.assembleUser(user);
} catch(Exception ex) {
System.out.println(ex);
return null;
}
}
}
WebAppInitializer
package com.x.y.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
#ComponentScan(basePackages = "com.x.y")
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
/* read configuration */
AnnotationConfigWebApplicationContext acwac = new AnnotationConfigWebApplicationContext();
acwac.setServletContext(servletContext);
acwac.scan("com.x.y.config");
acwac.refresh();
/* dispatcher-servlet */
ServletRegistration.Dynamic d = servletContext.addServlet("dispatcher", new DispatcherServlet(acwac));
//d.setInitParameter("contextConfigLocation", "/WEB-INF/spring-security.xml");
d.setLoadOnStartup(1);
d.addMapping("/");
/* context loader listiner */
//servletContext.addListener(new ContextLoaderListener(acwac));
}
}
WebAppConfig
package com.x.y.config;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.*;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.x.y")
#ImportResource("classpath:applicationContext.xml")
public class WebAppConfig {
/* spring view configuration */
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
/* hibernate data source configuration */
#Bean
public BasicDataSource basicDataSource() {
BasicDataSource dataSource = new BasicDataSource();
/* data source properties */
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/cadb_v1");
dataSource.setUsername("cadb_admin");
dataSource.setPassword("cadb_password");
dataSource.setDefaultAutoCommit(false);
return dataSource;
}
/* hibernate session factory configuration */
#Bean
public LocalSessionFactoryBean sessionFactoryBean() {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
/* session factory bean properties */
factoryBean.setDataSource(basicDataSource());
factoryBean.setPackagesToScan("com.x.y.dto");
return factoryBean;
}
#Bean
public SessionFactory sessionFactory() {
return sessionFactoryBean().getObject();
}
/* hibernate transaction manager configuration */
#Bean
public HibernateTransactionManager transactionManager(){
HibernateTransactionManager manager = new HibernateTransactionManager();
manager.setSessionFactory(sessionFactory());
return manager;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<session-config>
<session-timeout>1</session-timeout>
</session-config>
<!-- Spring Security Configuration -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-security.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
applicationContext.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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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-3.1.xsd">
<mvc:resources mapping="/resources/**" location="/resources/" />
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
spring-security.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<security:http auto-config="true" access-denied-page="/WEB-INF/view/error/access-denied.jsp">
<security:intercept-url pattern="/index*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/resources/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/**" access="ROLE_ADMIN" />
<security:form-login login-page="/index" default-target-url="/home" authentication-failure-url="/index?error=true" />
</security:http>
<bean id="userDetailsService" class="com.x.y.service.impl.UserDetailsServiceImpl" />
<bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService" />
</bean>
<security:authentication-manager>
<security:authentication-provider ref="daoAuthenticationProvider" />
<!-- <security:password-encoder hash="sha-256" />
</security:authentication-provider>-->
</security:authentication-manager>
</beans>
Please help me solve this problem, if you need more information let me know,
Note: Just this #Autowired not work
Regards,
FYA
Thank you who give me "This question does not show any research effort; it is unclear or not useful",
refers to this link
I just need add
<context:component-scan base-package="com.x.y" />
<context:annotation-config />
in spring-security.xml and it works now. Thanks, correct me if I'm wrong