Spring Security - UserDetailsService implementation - Login Fails - spring

I'm quite new to spring and i'having this issue with spring security.
Actually it only works without my custom UserDetailsService implementation.
Account and Role Objects
#Entity
#Table(name="ACCOUNT", uniqueConstraints = {#UniqueConstraint (columnNames = "USERNAME"), #UniqueConstraint (columnNames = "EMAIL")})
public class Account implements Serializable {
private static final long serialVersionUID = 2872791921224905344L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="ID")
private Integer id;
#Column(name="USERNAME")
#NotNull
private String username;
#Column(name="PASSWORD")
#NotNull
private String password;
#Column(name="EMAIL")
#NotNull
#Email
private String email;
#Column(name="ENABLED")
private boolean enabled;
#ManyToMany(cascade= CascadeType.ALL)
#JoinTable(name="ACCOUNT_ROLE", joinColumns = {#JoinColumn (name="ID_ACCOUNT")}, inverseJoinColumns ={ #JoinColumn (name="ID_ROLE")})
private Set<Role> roles = new HashSet<Role>(0);
Role
#Entity
#Table(name="ROLE", uniqueConstraints={#UniqueConstraint (columnNames="NAME")})
public class Role implements Serializable{
private static final long serialVersionUID = -9162292216387180496L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "NAME")
#NotNull
private String name;
#ManyToMany(mappedBy = "roles")
private Set<Account> accounts = new HashSet<Account>(0);
The adapter for the UserDetails
#SuppressWarnings({ "serial", "deprecation" })
public class UserDetailsAdapter implements UserDetails {
private Account account;
public UserDetailsAdapter(Account account) {this.account = account;}
public Account getAccount() {return account;}
public Integer getId(){return account.getId();}
public String getEmail () {return account.getEmail();}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for (Role r :account.getRoles()) {
authorities.add(new GrantedAuthorityImpl(r.getName()));
}
return authorities;
}
The custom UserDetailsService
#Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
#Inject AccountDao accountDao;
#Inject RoleDao roleDao;
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
Account account= accountDao.findByUsername(username);
if(account==null) {throw new UsernameNotFoundException("No such user: " + username);
} else if (account.getRoles().isEmpty()) {
throw new UsernameNotFoundException("User " + username + " has no authorities");
}
UserDetailsAdapter user = new UserDetailsAdapter(account);
return user;
}
The web.xml
<?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">
<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>
<!-- 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/appServlet/security- 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>
<!-- Creates the Filters to handle hibernate lazyload exception -->
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 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>
the root-context
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<context:property-placeholder properties-ref="deployProperties"/>
<!-- Remember to correctly locate the right file for properties configuration(example DB connection parameters) -->
<bean id="deployProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"
p:location="/WEB-INF/spring/appServlet/spring.properties" />
<context:annotation-config/>
<context:component-scan base-package="org.treci">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<import resource="/appServlet/data-context.xml"/>
The security context
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
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-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<http pattern="/resources" security="none" />
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/" access="permitAll"/>
<intercept-url pattern="/login" access="permitAll"/>
<intercept-url pattern="/login-success" access="hasRole('ROLE_ADMIN')"/>
<form-login login-page="/login"
default-target-url="/login-success"
authentication-failure-url="/login-failed"/>
<logout logout-success-url="/logout"/>
</http>
<beans:bean id="customUserDetailsService" class="org.treci.app.service.CustomUserDetailsService"></beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="customUserDetailsService">
</authentication-provider>
</authentication-manager>
</beans:beans>
I hope some of you can help, save me :)

Here's how I solved the problem:
in the CustomDetailsService I was returning a UserDetails Object by using an Adapter as you can see.
Looking at some tutorial I realized that i should return an org.springframework.security.core.userdetails.User Object.
Here's my new CustomDetailsService implementation:
#Transactional(readOnly=true)
#Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
#Inject AccountDao accountDao;
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
Account account= accountDao.findByUsername(username);
if(account==null) {throw new UsernameNotFoundException("No such user: " + username);
} else if (account.getRoles().isEmpty()) {
throw new UsernameNotFoundException("User " + username + " has no authorities");
}
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new User(
account.getUsername(),
account.getPassword().toLowerCase(),
account.isEnabled(),
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
getAuthorities(account.getRoles()));
}
public List<String> getRolesAsList(Set<Role> roles) {
List <String> rolesAsList = new ArrayList<String>();
for(Role role : roles){
rolesAsList.add(role.getName());
}
return rolesAsList;
}
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
public Collection<? extends GrantedAuthority> getAuthorities(Set<Role> roles) {
List<GrantedAuthority> authList = getGrantedAuthorities(getRolesAsList(roles));
return authList;
}
}

Related

#Autowired not working when using spring-security (neo4j as database)

I forked an example-spring-data-neo4j project, and build my own 'StigMod' project from it.
Everything works fine, until I tried to change the controller-service-repository structure of this project.
My Controller -> Service -> Repository structure.
#Controller
public class StigModController {
...
#Autowired
StigmodUserDetailsService stigmodUserDetailsService;
...
}
#Service
public class StigmodUserDetailsService implements UserDetailsService {
...
#Autowired
private UserRepository userRepository;
...
}
public interface UserRepository extends GraphRepository<User> {
User findByMail(String mail);
}
Structure in the example:
#Controller
public class AuthController {
...
#Autowired
UserRepository userRepository;
...
}
public interface UserRepository extends GraphRepository<User>, CineastsUserDetailsService {
User findByLogin(String login);
}
#Service
public class CineastsUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
}
public class UserRepositoryImpl implements CineastsUserDetailsService {
#Autowired
private UserRepository userRepository;
}
After my refactoring, a problem popped out:
The StigmodUserDetailsService class is annotated with #Service. Component scan is enabled in package net.stigmod, and my IDE actually could recognize all the #Autowire dependencies in all files.
However, the autowired field stigmodUserDetailsService in StigModController.java could not be initialized during deployment.
I tried several methods proposed by people in some similar questions, but they did not work. I guess there is soming wrong with the spring-security dymamic object feature, but I am not sure.
I posted most of the related complete codes below. Hope someone could help me out. Thank you so much!
### ERROR in Tomcat Localhost Log during deployment ###
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stigModController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: net.stigmod.service.StigmodUserDetailsService net.stigmod.controller.StigModController.stigmodUserDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [net.stigmod.service.StigmodUserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
...
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: net.stigmod.service.StigmodUserDetailsService net.stigmod.controller.StigModController.stigmodUserDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [net.stigmod.service.StigmodUserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 56 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [net.stigmod.service.StigmodUserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 58 more
### web.xml ###
<?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">
<display-name>Spring MVC Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-security.xml
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<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>StigMod</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>StigMod</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
</web-app>
### applicationContext.xml ###
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config/>
<context:spring-configured/>
<context:component-scan base-package="net.stigmod">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<tx:annotation-driven mode="proxy"/>
</beans>
### applicationContext-security.xml ###
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<context:component-scan base-package="net.stigmod">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<security:global-method-security secured-annotations="enabled">
</security:global-method-security>
<security:http> <!-- use-expressions="true" -->
<security:intercept-url pattern="/" access="isAnonymous()"/>
<security:intercept-url pattern="/static/**" access="permitAll"/>
<security:intercept-url pattern="/about" access="permitAll"/>
<security:intercept-url pattern="/signin*" access="isAnonymous()"/>
<security:intercept-url pattern="/signup*" access="isAnonymous()"/>
<security:intercept-url pattern="/**" access="isFullyAuthenticated()"/>
<security:form-login login-page="/signin"
authentication-failure-url="/signin?login_error=true"
default-target-url="/user"
login-processing-url="/signin"
username-parameter="mail"
password-parameter="password"/>
<security:access-denied-handler error-page="/denied" />
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="stigmodUserDetailsService">
<security:password-encoder hash="md5">
<security:salt-source system-wide="xxxxxx"/>
</security:password-encoder>
</security:authentication-provider>
</security:authentication-manager>
</beans>
### StigMod-servelet.xml ###
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="net.stigmod.controller"/>
<mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
<mvc:annotation-driven/>
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="configLocation" value="/WEB-INF/velocity.properties"/>
<property name="resourceLoaderPath" value="/WEB-INF/velocity/"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".vm"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
</bean>
</beans>
### Application.java ###
package net.stigmod;
import net.stigmod.util.config.Config;
import net.stigmod.util.config.ConfigLoader;
import net.stigmod.util.config.Neo4j;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.server.Neo4jServer;
import org.springframework.data.neo4j.server.RemoteServer;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableNeo4jRepositories("net.stigmod.repository")
#EnableTransactionManagement
#ComponentScan("net.stigmod")
public class Application extends Neo4jConfiguration {
// Common settings
private Config config = ConfigLoader.load();
private Neo4j neo4j = config.getNeo4j();
private String host = neo4j.getHost();
private String port = neo4j.getPort();
private String username = neo4j.getUsername();
private String password = neo4j.getPassword();
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory("net.stigmod.domain");
}
#Override
#Bean
public Neo4jServer neo4jServer() {
return new RemoteServer("http://" + host + ":" + port, username, password);
}
#Override
#Bean
#Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception {
return super.getSession();
}
}
### StigModController.java ###
package net.stigmod.controller;
import net.stigmod.domain.node.User;
import net.stigmod.service.StigmodUserDetailsService;
import net.stigmod.util.config.Config;
import net.stigmod.util.config.ConfigLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.stereotype.Controller;
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.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#Controller
public class StigModController {
// Common settings
private Config config = ConfigLoader.load();
private String host = config.getHost();
private String port = config.getPort();
#Autowired
StigmodUserDetailsService stigmodUserDetailsService;
private final static Logger logger = LoggerFactory.getLogger(UserController.class);
// front page
#RequestMapping(value="/", method = RequestMethod.GET)
public String index(ModelMap model) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "index");
return "index";
}
// about this web app
#RequestMapping(value="/about", method = RequestMethod.GET)
public String about(ModelMap model) {
final User user = stigmodUserDetailsService.getUserFromSession();
model.addAttribute("user", user);
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "about");
return "about";
}
// sign up page GET
#RequestMapping(value="/signup", method = RequestMethod.GET)
public String reg(ModelMap model, HttpServletRequest request) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "Sign Up");
// CSRF token
CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrfToken != null) {
model.addAttribute("_csrf", csrfToken);
}
return "signup";
}
// sign up page POST
#RequestMapping(value="/signup", method = RequestMethod.POST)
public String regPost(
#RequestParam(value = "mail") String mail,
#RequestParam(value = "password") String password,
#RequestParam(value = "password-repeat") String passwordRepeat,
ModelMap model, HttpServletRequest request) {
try {
stigmodUserDetailsService.register(mail, password, passwordRepeat);
return "redirect:/user";
} catch(Exception e) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "Sign Up");
// CSRF token
CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrfToken != null) {
model.addAttribute("_csrf", csrfToken);
}
model.addAttribute("mail", mail);
model.addAttribute("error", e.getMessage());
return "signup";
}
}
// sign in page GET (POST route is taken care of by Spring-Security)
#RequestMapping(value="/signin", method = RequestMethod.GET)
public String login(ModelMap model, HttpServletRequest request) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "Sign In");
// CSRF token
CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrfToken != null) {
model.addAttribute("_csrf", csrfToken);
}
return "signin";
}
// sign out
#RequestMapping(value="/signout", method = RequestMethod.GET)
public String logout (HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/signin";
}
// Denied page GET
#RequestMapping(value="/denied", method = RequestMethod.GET)
public String reg(ModelMap model) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "Denied");
return "denied";
}
}
### UserRepository.java ###
package net.stigmod.repository.node;
import net.stigmod.domain.node.User;
import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends GraphRepository<User> {
User findByMail(String mail);
}
### StigmodUserDetails.java ###
package net.stigmod.service;
import net.stigmod.domain.node.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
public class StigmodUserDetails implements UserDetails {
private final User user;
public StigmodUserDetails(User user) {
this.user = user;
}
#Override
public Collection<GrantedAuthority> getAuthorities() {
User.SecurityRole[] roles = user.getRole();
if (roles == null) {
return Collections.emptyList();
}
return Arrays.<GrantedAuthority>asList(roles);
}
#Override
public String getPassword() {
return user.getPassword();
}
#Override
public String getUsername() {
return user.getMail();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
public User getUser() {
return user;
}
}
### StigmodUserDetailsService.java ###
package net.stigmod.service;
import net.stigmod.domain.node.User;
import net.stigmod.repository.node.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
public class StigmodUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
public StigmodUserDetailsService() {}
public StigmodUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
#Override
public StigmodUserDetails loadUserByUsername(String mail) throws UsernameNotFoundException {
final User user = userRepository.findByMail(mail);
if (user == null) {
throw new UsernameNotFoundException("Username not found: " + mail);
}
return new StigmodUserDetails(user);
}
public User getUserFromSession() {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
Object principal = authentication.getPrincipal();
if (principal instanceof StigmodUserDetails) {
StigmodUserDetails userDetails = (StigmodUserDetails) principal;
return userDetails.getUser();
}
return null;
}
#Transactional
public User register(String mail, String password, String passwordRepeat) {
User found = userRepository.findByMail(mail);
if (found != null) {
throw new RuntimeException("Email already taken: " + mail);
}
if (password == null || password.isEmpty()) {
throw new RuntimeException("No password provided.");
}
if (passwordRepeat == null || passwordRepeat.isEmpty()) {
throw new RuntimeException("No password-repeat provided.");
}
if (!password.equals(passwordRepeat)) {
throw new RuntimeException("Passwords provided do not equal.");
}
User user = userRepository.save(new User(mail, password, User.SecurityRole.ROLE_USER));
setUserInSession(user);
return user;
}
void setUserInSession(User user) {
SecurityContext context = SecurityContextHolder.getContext();
StigmodUserDetails userDetails = new StigmodUserDetails(user);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, user.getPassword(), userDetails.getAuthorities());
context.setAuthentication(authentication);
}
}

Spring + Hibernate DAO injection fails in Netbeans

I have controller class LoginData.java
#Controller
#ManagedBean(name = "login")
#SessionScoped
public class LoginData implements Serializable{
#Autowired
private LoginDAO loginDao;
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void validateUser(){
try{
loginDao.login(username, password);
}catch(BusinessException e){
}
}
}
I am trying to autowire this Dao and its implementation:
LoginDAO
public interface LoginDAO {
public boolean login(String username, String password)throws BusinessException;
public boolean register(String username, String password, UserType type)throws BusinessException;
}
LoginDAOImpl
public class LoginDAOImpl implements LoginDAO{
private String username;
private String password;
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public boolean login(String username, String password) throws BusinessException{
Query query = sessionFactory.getCurrentSession().createQuery(
"SELECT u FROM User u WHERE u.username=:un");
query.setParameter("un", username);
if(query.list().size()==0)throw new BusinessException("No user in database!");
User user = (User)(query.list().get(0));
return getHashMD5(password).equals(user.getPassword());
}
#Override
public boolean register(String username, String password, UserType type) throws BusinessException{
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public static String getHashMD5(String string) throws BusinessException{
try {
MessageDigest md = MessageDigest.getInstance("MD5");
BigInteger bi = new BigInteger(1, md.digest(string.getBytes()));
return bi.toString(16);
} catch (Exception ex) {
throw new BusinessException(ex.getMessage());
}
}
}
I am also trying to inject sessionFactory in DAO implementation, I don't know if this code will work. My xml for configuration:
dispatcher-servlet.xml
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
<bean id="loginDAO" class="rs.ac.bg.etf.services.LoginDAOImpl"/>
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</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>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
I get null pointer exception when dao method is called in controller from JSF form. Anyone knows what could be the problem?
PS: xml files are mostly generated by Netbeans IDE.
You're missing the #Repository annotation for the autowiring to work.
Try this:
#Repository("LoginDAO")
public class LoginDAOImpl implements LoginDAO

Spring dependency config problems

Hello guys,
I am new to Spring and currently I am working on a web project in which I use Spring MVC and Spring dependency injection. I have three classes. UserService, HomeController and User. In HomeController I invoke UserService's fetchUser method which returns me a new Instance of the User class. It is a simple logic I use to reproduce my real project problem. I am not using any database in this simple project. When I invoke the fetchUserMethod I am getting a NullPointerException. I am using Glassfish 4.0. Could you please help me ?
Thank you !
Here is my web.xml
`<?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/aplicationContext.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/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>`
Here is my 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="userService" class="services.UserService"/>
<bean id="homeController" class="controllers.HomeController">
<property name="userService" ref="userService"/>
</bean>
</beans>
Here is my servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<context:component-scan base-package="controllers"/>
</beans:beans>
Here is my HomeController class
#Controller
public class HomeController {
private UserService userService;
#RequestMapping(value = "/home")
public ModelAndView homePage(HttpServletRequest request, HttpServletResponse response, HttpSession session){
User user = userService.fetchUser();
return new ModelAndView("home", "displayName", user.getUserName());
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
Here is my User class
public class User {
private String userName;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Here is my UserService class
public class UserService {
public User fetchUser(){
User user = new User();
user.setUserName("test");
return user;
}
}
You miss the #Autowired annotation in your HomeController:
#Autowired
private UserService userService;
Remove homeController bean defintiion.
Since you are using <context:component-scan base-package="controllers"/> there is no need to declare homeController bean - it will be created automatically because it's annotated with annotation #Controller.
Autowire UserService into HomeController using#Autowired` annotation. There are 3 ways you can do it:
field injection:
#Autowired
private UserService userService;
setter injection
#Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
constructor injection:
#Autowired
public HomeController(UserService userService) {
this.userService = userService;
}
Preferred way is to always use constructor injection
Remove UserService getters and setters in HomeController.
In the end, HomeController class should look like:
#Controller
public class HomeController {
private final UserService userService;
#Autowired
public HomeController(UserService userService) {
this.userService = userService;
}
#RequestMapping(value = "/home")
public ModelAndView homePage(HttpServletRequest request, HttpServletResponse response, HttpSession session){
User user = userService.fetchUser();
return new ModelAndView("home", "displayName", user.getUserName());
}
}
This way Eclipse marks the default constructor line with error. If I remove the default constructor glassfish says it cannot initialize UserService because there is no default constructor.
public class UserService {
public UserService(){}
private final UserDao userDao;
#Autowired
public UserService(UserDao userDao){
this.userDao = userDao;
}
public User fetchUser(){
User user = userDao.fetchUser();
return user;
}
}

getting empty form session bean in jsf

I have set session bean after login, and print the value from session bean it prints in xhtml file but while i go to the next page or bean session bean return empty it automatically reset the value.
I am using the primeface 4.0, jsf 2.0 and ejb 3.0 for web application.
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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value> </context-param> -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>ui-lightness</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.CHECK_ID_PRODUCTION_MODE</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.VIEW_UNIQUE_IDS_CACHE_ENABLED</param-name>
<param-value>true</param-value>
</context-param>
<mime-mapping>
<extension>xlsx</extension>
<mime-type>text/xlsx</mime-type>
</mime-mapping>
</web-app>
//Setting user from loginMB having viewscope bean.
UserMB
#SessionScoped
#ManagedBean(name = "userMB")
public class UserMB extends AbstractMB implements Serializable {
public static final String INJECTION_NAME = "#{userMB}";
private static final long serialVersionUID = 1L;
private User user;
#EJB
private UserEJB userEJB;
public String logOut() {
getRequest().getSession().invalidate();
return "/index.xhtml?faces-redirect=true";
}
private HttpServletRequest getRequest() {
return (HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
}
public User getUser() {
if (user == null) {
user = new User();
}
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<User> getUserList() {
if (userList == null) {
userList = userEJB.findAll();
}
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
}
CampMB
#ManagedBean
#ViewScoped
public class CampMB extends AbstractMB implements Serializable {
private static final long serialVersionUID = 1L;
#ManagedProperty("#{userMB}")
private UserMB userMB;
public UserMB getUserMB() {
return userMB;
}
public void setUserMB(UserMB userMB) {
this.userMB = userMB;
}
private User user;
private Camp camp;
private List<CampDTO> listCamp;
#EJB
private CampEJB campEJB;
#EJB
private MemberEJB memberEJB;
#EJB
private CodeValueEJB codeEJB;
TimeZone timeZone = TimeZone.getDefault();
public TimeZone getTimeZone() {
return timeZone;
}
public void setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone;
}
public List<CampDTO> getListCamp() {
Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
UserMB managedBean = (UserMB) sessionMap.get("userMB");
System.out.println("test use==" + managedBean.getUser().getId());
System.err.println("Session"+getUserMB().getUser().getId());
if (listCamp == null) {
listCamp = new ArrayList<CampDTO>();
}
listCamp = ConvertUtils.convertCampToDTO(campEJB.findAll());
return listCamp;
}
public void setListCamp(List<CampDTO> listCamp) {
this.listCamp = listCamp;
}
public User getUser() {
if (user == null) {
user = new User();
}
return user;
}
public void setUser(User user) {
this.user = user;
}
}
I am trying different techniques getting from search but no one works for me?
Is there any configuration for it or how to set/get session bean properly.

My repository can't initialize automatically while using Spring Data JPA

I am trying to add spring data jpa to my spring-mvc web project after exploring a couple of tutorials. But I found my repository can't initialize automatically, I got NullPointerException in my service class. Please see my following sample code:
My repository:
public interface SubjectRepository extends JpaRepository<PSubject, String>{
public Page<PSubject> findByType(String title, Pageable pageable);
public Page<PSubject> findByType(String title);
public Page<PSubject> findByMacaddress(String macaddress, Pageable pageable);
public Page<PSubject> findByMacaddress(String macaddress);
public Page<PSubject> findByUri(String uri);
}
My controller:
#Controller
#RequestMapping("/subject")
public class VPSubjectController
{
....
#RequestMapping("/{id}.htm")
public ModelAndView detail(#PathVariable String id)
{
ModelAndView mav = new ModelAndView("subject/detail");
PSubject subject = subjectService.get(id);
....
}
}
My Service:
#Service("subjectService")
public class SubjectServiceImpl extends VPService implements SubjectService
{
#Autowired
private SubjectRepository subjectRepository;
......
#Override
#Transactional(propagation=Propagation.REQUIRED, readOnly=true)
public PSubject get(String subject) {
PSubject subObj = subjectRepository.findOne(subject);
return subObj;
}
.....
My configuration:
<?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:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
....
<jpa:repositories base-package="com.mypacke.repository" repository-impl-postfix="Impl" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>
....
I found in this line subjectRepository.findOne(subject) ,subjectRepository is null,
My question is similar this post
#Autowired annotation is activated by the statement:
<context:component-scan base-package="base.package"/>
If u do that, it would be initialized

Resources