No bean named 'CustomAuthenticationProvider' is defined - java

I am trying to switch from a working jdbc-user-service to a customAuthenticationProvider which implements AuthenticationProvider, however spring is not finding it. I'm not sure if it has to do with something about having my configurations in xml or what is wrong. I started out with one in my dispatcher servlet however on advice from things that I read I added one to my spring-security.xml as well which didn't make any difference. Any ideas what is wrong with my configuration?
Thanks!
mvc-dispatch-servlet.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-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:component-scan base-package="com.mkyong.*" />
<!-- Currently not working. Made a work around by having resources at /resources and pages at /pages -->
<mvc:resources location="/resources/" mapping="/resources/" />
<!-- also add the following beans to get rid of some exceptions -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"><value>/WEB-INF/pages/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
</beans>
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
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-3.2.xsd>
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<!-- login page must be available to all. The order matters, if this is after something which secures the page this will fail. -->
<intercept-url pattern="/pages/login" access="permitAll" />
<intercept-url pattern="/pages/admin/**" access="hasRole('_admin')" />
<intercept-url pattern="/pages/trade/**" access="hasRole('_trader')" />
<intercept-url pattern="/pages/discover/**" access="hasRole('_users')" />
<!-- access denied page -->
<access-denied-handler error-page="/pages/403" />
<form-login
login-page="/pages/login"
default-target-url="/pages/trade/index"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<logout logout-url="/pages/logout" logout-success-url="/pages/login?logout" />
<!-- enable csrf protection -->
<csrf/>
</http>
<!-- Select users and user_roles from database -->
<authentication-manager>
<authentication-provider ref="CustomAuthenticationProvider"/>
<!--<jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"select email,pwhash, enabled from users where email=?"
authorities-by-username-query=
"select email, groupname from usergroups where email =? " />
</authentication-provider> -->
</authentication-manager>
</beans:beans>
CustomAuthenticationProvider.java
package com.mkyong.web.controller;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
User user = new User();
user.name = authentication.getName();
user.password = authentication.getCredentials().toString();
try {
user.id = Instance.users.getUserByEmail(user.name).getUserID();
} catch (Exception e) {
Instance.debug("CustomAuthenticationProvider authenticate","Error getting user" + e);
}
// use the credentials to try to authenticate against the third party system
if (passVerify(user)) {
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
try {
UserRoles roles = Instance.users.getUser(user.id).roles;
userRolesToDatabaseRoles(roles, grantedAuths);
} catch (Exception e) {
Instance.debug("CustomAuthenticationProvider authenticate","Error getting user" + e);
}
return new UsernamePasswordAuthenticationToken(user.name, user.password, grantedAuths);
} else {
Instance.debug("CustomAuthenticationProvider authenticate","Unable to authenticate");
return null;
}
}
private void userRolesToDatabaseRoles(UserRoles roles, List<GrantedAuthority> grantedAuths) {
if(roles.admin){
grantedAuths.add(new SimpleGrantedAuthority("_admin"));
}
if(roles.trader){
grantedAuths.add(new SimpleGrantedAuthority("_trader"));
}
if(roles.analyst){
grantedAuths.add(new SimpleGrantedAuthority("_users"));
}
}
private boolean passVerify(User user) {
StringBuffer MD5 = getMD5(user);
try {
//User still has an MD5 password, so change them over to bcrypt
if(MD5.toString().equals(Instance.users.getPasswordHash(user.name))){
String hashedPassword = getBcrypt(user).toString();
instance.users.changePassword(user.id, hashedPassword);
return true;
}
} catch (Exception e) {
instance.debug("CustomAuthenticationProvider passVerify","Error getting userpassword" + e);
}
StringBuffer bcrypt = getBcrypt(user);
if(bcrypt.toString().equals(user.password)){
return true;
}
return false;
}
public StringBuffer getBcrypt(User user) {
//This sets how many rounds bcrypt will run. The high the number the longer it takes which will slow down user login, however it also slows
//down a would be attacker. This is a key advantage of bcrypt over other algorithms. *IMPORTANT* changing the strength will result in needing to
//rehash all passwords. This is very doable but requires more work.
//See http://crypto.stackexchange.com/questions/3003/do-i-have-to-recompute-all-hashes-if-i-change-the-work-factor-in-bcrypt
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(10);
StringBuffer hashedPassword = new StringBuffer();
hashedPassword.append(passwordEncoder.encode(user.password));
return hashedPassword;
}
public StringBuffer getMD5(User user) {
StringBuffer sb = null;
MessageDigest md;
String original = "a";
try {
md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
} catch (NoSuchAlgorithmException e) {
instance.debug("CustomAuthenticationProvider hashMD5","Error getting MD5 instance" + e);
}
return sb;
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
public class User{
public long id;
protected String name, password;
}
}
Not sure if web.xml is necessary to post but here it is:
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">
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>InitServlet</servlet-name>
<servlet-class>servletInitServlet</servlet-class>
<init-param>
<param-name>configfile</param-name>
<param-value>C:/transmetric/dev/java/WebContent/WEB-INF/config.properties</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>AdminServlet</servlet-name>
<servlet-class>servlet.admin</servlet-class>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>servlet.user</servlet-class>
<load-on-startup>4</load-on-startup>
</servlet>
<servlet>
<servlet-name>SignupUserServlet</servlet-name>
<servlet-class>servlet.user.SignupUserServlet</servlet-class>
<load-on-startup>5</load-on-startup>
</servlet>
<servlet>
<servlet-name>ReceiveFile</servlet-name>
<servlet-class>servlet.user</servlet-class>
<load-on-startup>6</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/pages/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AdminServlet</servlet-name>
<url-pattern>/AdminServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/UserServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SignupUserServlet</servlet-name>
<url-pattern>/SignupUserServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ReceiveFile</servlet-name>
<url-pattern>/ReceiveFile</url-pattern>
</servlet-mapping>
<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,
/WEB-INF/spring-database.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>

Try defining your CustomAuthenticationProvider bean in spring-security xml instead of using #Component annotation.
Or you can also try to put <context:component-scan base-package="com.mkyong.*" /> in your security xml

Change
<authentication-provider ref="CustomAuthenticationProvider"/>
to (not the uncapitalized bean name)
<authentication-provider ref="customAuthenticationProvider"/>
By default, the bean names for autodetected components annotated with #Component is the uncapitalized non-qualified class name. In your case this will be customAuthenticationProvider.

In my case an exception was caused by actually missing .class files due to bad Maven build:
(YourApp)/target/classes
(YourApp)/target/(YourApp).war/WEB-INF/classes/
(YourApp)/target/(YourApp).war/WEB-INF/lib/
The root cause was Eclipse problem: it switched to use embedded Maven while I always use external one. To fix it I had to:
Preferences > Maven > Installations, setup external Maven
Delete project from workspace
Delete all derived files/folders in project folder (target/, bin/, .settings/, .classpath & .project), leave only pom.xml and src/.
File > Import... > Existing Maven Projects, select my project.
Once rebuilt, all required classes were there.

Related

spring security session management for concurrency and session timeout not working

I am using spring security to stop user from multiple logins and invalidating session after session timeout which redirects user to a login page.
Below is web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>GrievancePortal</display-name>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml /WEB-INF/springSecurity.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>
<servlet>
<servlet-name>GrievanceServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/webController.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>GrievanceServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>/home/error</location>
</error-page>
<session-config>
<session-timeout>1</session-timeout>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
</web-app>
springsecuirty.xml
<bean:beans xmlns="http://www.springframework.org/schema/security"
xmlns:bean="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-3.2.xsd">
<http auto-config="true" disable-url-rewriting="true"
use-expressions="true" authentication-manager-ref="authManager"
access-denied-page="/home/error">
<form-login always-use-default-target="true" login-page="/home/AuthCheck"
login-processing-url="/home/checkAuth" default-target-url="/user/welcome"
username-parameter="username" password-parameter="password"
authentication-failure-url="/home/AuthCheck?error" />
<logout delete-cookies="JSESSIONID" invalidate-session="true"
logout-url="/logout" logout-success-url="/home/logout" />
<intercept-url pattern="/" access="isAuthenticated()" />
<intercept-url pattern="/user/**" access="isAuthenticated()" />
<intercept-url pattern="/admin/**" access="isAuthenticated()" />
<session-management session-fixation-protection="newSession"
invalid-session-url="/home/sessionexpired">
<concurrency-control max-sessions="1"
expired-url="/home/sessionexpired" />
</session-management>
</http>
<authentication-manager id="authManager">
<authentication-provider ref="customAuthProvider">
</authentication-provider>
</authentication-manager>
<bean:bean id="customAuthProvider" class="com.GrievancePortal.Service.AuthProvider"></bean:bean>
</bean:beans>
CustomAuthProvider
package com.GrievancePortal.Service;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.GrievancePortal.Dao.AuthProviderDao;
import com.GrievancePortal.Pojo.UserDetails;
import com.sun.xml.internal.ws.client.ResponseContext;
public class AuthProvider implements AuthenticationProvider{
#Autowired
private AuthProviderDao dao;
#Autowired
private UserDetailsSer userDetailsSer;
#Override
public Authentication authenticate(Authentication Object)
throws AuthenticationException {
String userName=Object.getName();
String passWord=Object.getCredentials().toString();
UserDetails user=null;
try{
user=(UserDetails) userDetailsSer.loadUserByUsername(userName);
if(!user.getPassword().equals(passWord)){
throw new BadCredentialsException("Invalid Credentials");
}
}
catch (IncorrectResultSizeDataAccessException e){
throw new BadCredentialsException("User Doesn't Exist Please Signup First");
}
/*HttpServletRequest request =
((ServletRequestAttributes) RequestContextHolder.
currentRequestAttributes()).
getRequest();
sessionAuthenticationStrategy.onAuthentication(Object,null,null);*/
return new UsernamePasswordAuthenticationToken(user, null,null);
}
#Override
public boolean supports(Class<?> authentication) {
// TODO Auto-generated method stub
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
CustomUserDetailsSer
package com.GrievancePortal.Service;
import org.springframework.beans.factory.annotation.Autowired;
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.GrievancePortal.Dao.AuthProviderDao;
#Service
public class UserDetailsSer implements UserDetailsService{
#Autowired
private AuthProviderDao dao;
#Override
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException {
com.GrievancePortal.Pojo.UserDetails userDetails=dao.getAuthUser(userName);
return userDetails;
}
}
The userDetails object returend by CustomUserDetails service overrides hashcode and equals method and implements UserDetails provide by Spring Security

Default RequestMapping does not get invoked

I am stuck with a strange situation when loading up my web application on tomcat. The welcome file gets loaded well, but the controller part is not getting invoked.
Here is my Project Directory:
Here is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/application-context.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>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/WEB-INF/views/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Here is my controller class
package com.bng.monitor.controller;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
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.servlet.ModelAndView;
import com.bng.monitor.util.Utility;
#Controller
public class MonitoringController {
private static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
private static SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//private static List<DBObject> pipeline=new ArrayList<DBObject>();
static HashMap<String, String> hmLatestDateTime=new HashMap<String, String>();
#Autowired
private Utility utility;
private static #Value("${pageRefresh}") String pageRefresh;
public Utility getUtility() {
return utility;
}
public void setUtility(Utility utility) {
this.utility = utility;
}
public static String getPagerefresh() {
return pageRefresh;
}
public void setPagerefresh(String pagerefresh) {
MonitoringController.pageRefresh = pagerefresh;
}
#RequestMapping(value="/version", method=RequestMethod.GET)
public ModelAndView getVersion(){
System.out.println("inside controller..");
ModelAndView mav=null;
try
{
mav=new ModelAndView("version");
if(Utility.version!=null)
mav.addObject("versionapp", Utility.version);
else if(Utility.version == null || Utility.version.equals(""))
mav.addObject("versionapp", "property not defined.. :)");
} catch (Exception e) {
e.printStackTrace();
}
return mav;
} // end of getVersion()
#RequestMapping(value="/reloadftp",method=RequestMethod.GET)
public void reloadFtpConfig(){
try {
this.utility.getFtpCred();
} catch (Exception e) {
e.printStackTrace();
}
}
#RequestMapping(value="/")
public String displayGui(ModelMap model) {
try
{
System.out.println("<<< inside root mapping for index.jsp display >>>");
model.addAttribute("map", Utility.hmServerFtpCred);
model.addAttribute("pagerefresh", pageRefresh);
String key=null;
String combinedJson=null;
JSONArray jsonArray=null;
JSONObject jsonObject1=null;
JSONObject jsonObject2=null;
String tempMod=null;
String tempStat=null;
String cpu=null;
String ram=null;
for(Map.Entry entry: Utility.hmServerFtpCred.entrySet()){
key = (String) entry.getKey();
// for each key get combinedJson (and do so in a loop as the json formed there may not be valid) and parse it to get module and system properties cached into hmGuiData
//TODO add logic to alter GUI to give some indication(color based) that the data is not updated since long time.
combinedJson = Utility.getStats(key);
jsonArray = new JSONArray(combinedJson);
System.out.println(">>> combined JSON: "+jsonArray.toString());
JSONArray moduleArr = jsonArray.getJSONObject(0).getJSONObject("details").getJSONArray("module");
for(int index=0; index<moduleArr.length() ; index++)
{
tempMod=moduleArr.getJSONObject(index).getString("module_name");
tempStat=moduleArr.getJSONObject(index).getString("live");
Utility.hmGuiData.put(key+"_"+tempMod.toLowerCase(), tempStat);
}
Utility.hmGuiData.put(key+"_"+"cpu", jsonArray.getJSONObject(1).getJSONObject("details").getString("cpu"));
Utility.hmGuiData.put(key+"_"+"ram", jsonArray.getJSONObject(1).getJSONObject("details").getString("ram"));
/*jsonObject1 = (JSONObject) jsonArray.get(0);
jsonObject2 = (JSONObject) jsonArray.get(1);
jsonObject1.getJSONObject("details").*/
} // end of inner for
System.out.println(">>> Utility.hmGuiData: "+Utility.hmGuiData);
model.addAttribute("guidata", Utility.hmGuiData);
return "index";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#RequestMapping(value="/getstatsone",method=RequestMethod.GET)
public void getStatsOne(HttpServletRequest req,HttpServletResponse resp){
}
#RequestMapping(value="/getopco",method=RequestMethod.GET)
public void getOpco(HttpServletRequest req,HttpServletResponse resp) {
PrintWriter pw=null;
System.out.println(">>> inside /getopco");
JSONObject json=null;
try
{
pw=resp.getWriter();
json=new JSONObject(Utility.hmServerFtpCred);
pw.println(json);
}
catch (Exception e)
{
e.printStackTrace();
}finally{
try {
if(pw!=null)
pw.close();
} catch (Exception ee) {
ee.printStackTrace();
}
}
}
}//end of Controller class
and here is my application-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:c="http://www.springframework.org/schema/c"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:core="http://activemq.apache.org/schema/core" xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.7.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.bng.monitor" />
<bean id="properties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/config.properties" />
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources location="/resources/css/**" mapping="/css/**"/>
<mvc:resources location="/resources/img/**" mapping="/img/**"/>
<mvc:resources location="/resources/js/**" mapping="/js/**"/>
<!-- <mvc:resources location="/WEB-INF/views/**" mapping="/js/**"/> -->
<mvc:annotation-driven />
<mvc:resources mapping="/*" location="/WEB-INF/views/" />
</beans>
Now there are two things happening...
1. When I make the url pattern as /* and make the request, then only the controller gets invoked, welcome jsp is not loaded and tomcat gives error 404, the requested resource is not available.
When i change the url pattern to /, then only welcome page gets loaded and no backend controller specific mapping is called.
In both the cases, my application is not loaded.
Please help me out to load the web app successfully.
Removing the following welcome list from web.xml solved the issue.
So, I just removed the following lines from web.xml
<welcome-file-list>
<welcome-file>/WEB-INF/views/index.jsp</welcome-file>
</welcome-file-list>

Tomcat/ApplicationContext not able to find out Filter class

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/j2ee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Self Service Portal</display-name>
<welcome-file-list>
<welcome-file>home.html</welcome-file>
<welcome-file>default.html</welcome-file>
</welcome-file-list>
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET, POST, PUT, DELETE, OPTIONS, HEAD</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>login</filter-name>
<filter-class>com.app.api.filter.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>login</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!-- Spring Context Listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>
</web-app>
Custom filter class:-
package com.app.api.filter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import com.fasterxml.jackson.databind.ObjectMapper;
#WebFilter("/*")
public class AuthenticationFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationFilter.class);
public AuthenticationFilter() {
System.out.println("Authentication - default filter !");
}
public void destroy() {
System.out.println("Authentication - destroy !");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
LOGGER.debug("Request authentication!");
HttpServletRequest httpRequest = (HttpServletRequest) request;
String uri = httpRequest.getRequestURI();
if(uri.equals("/app-api/login") || uri.equals("/app-api/logout")) {
chain.doFilter(request, response);
return;
}
HttpSession session = httpRequest.getSession(false);
if(session == null || session.getAttribute("user") == null) {
writeInvalidCredentialResponse((HttpServletResponse) response);
} else {
chain.doFilter(request, response);
}
}
private void writeInvalidCredentialResponse(HttpServletResponse response) throws IOException {
Map<String, String> errorResponse = new HashMap<String, String>();
errorResponse.put("message", "Please login with right credentials!");
ObjectMapper mapper = new ObjectMapper();
String responseMessage = mapper.writeValueAsString(errorResponse);
LOGGER.debug("Invalid request authentication!");
LOGGER.debug(responseMessage);
response.getWriter().write(responseMessage);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("Authentication - init !");
}
}
Project hierarchy:-
A - parent maven module
B - RESTful webservices sub module (contains - /WEB-INF/web.xml, /WEB-INF/dispatcher-servlet.xml)
C - persistence layer sub module (contains - /resources/applicationContext.xml, /resources/persistence.xml)
Please help me to resolve this issue to make my both spring context up and running (ui - webservices and persistence)
Many thanks in advance !
app-api
/app-api/src/main/webapp/WEB-INF/dispatcher-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: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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<import resource="classpath:/applicationContext-data.xml" />
<context:annotation-config />
<context:component-scan base-package="com.app" />
<context:property-placeholder location="classpath:*.properties" />
<mvc:annotation-driven/>
</beans>
app-data
/app-data/src/main/resources/applicationContext-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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-2.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- ************* JPA/Hibernate configuration ************* -->
<bean
name="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.app.data.*" />
<property name="persistenceXmlLocation" value="classpath:persistence.xml" />
<property name="persistenceUnitName" value="persistence-unit" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
</bean>
<bean
id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean
id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/app"
p:username="root"
p:password="root123"
p:initialSize="5"
p:maxActive="10">
</bean>
<context:component-scan base-package="com.app.data.*" />
<tx:annotation-driven />
</beans>
Let's see the exception:
java.lang.ClassNotFoundException: com.adobe.ssp.api.filter.AuthenticationFilter
There was a problem with your classpath, the class "com.adobe.ssp.api.filter.AuthenticationFilter" was not found. Please make sure this class is contained in: YOUR_APP\WEB-INF\classes or YOUR_APP\WEB-INF\lib
Try removing #WebFilter and make sure about your init method overriding as we can't see that in code provided.

Spring security using http authentication based on xml

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....:)

managed bean field is null when invoke bean method primefaces jsf

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.

Categories

Resources