I would like to ask from some insight as I'm not sure what is wrong here. I need to add authentication via database stored details so I'm trying to do that. The problem being that every userdetails I use to access the main pages returns the login failed page.
The DAO layer
#Transactional
#Repository ("staffDAO")
public class StaffDAO extends AbstractDAO<Staff>{
public StaffDAO() {
super(Staff.class);
}
#Autowired
#Resource(name="sessionFactory")
private SessionFactory sessionFactory;
private Transaction transaction;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;}
#SuppressWarnings("unchecked")
public List<Authority> getAuthority() {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Authority ");
return query.list();}
public void saveAuthority(Authority authority) {
try {
Session session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
session.save(authority);
transaction.commit();
} catch (Exception e) {
transaction.rollback();}}
#Transactional("hibernatetransactionManager")
public Staff getUserByUserName(String userName){
Query queryResult;
queryResult =getCurrentSession().createQuery("from Staff where username=:userName");
queryResult.setParameter("userName", new String(userName));
return (Staff) queryResult.list().get(0)}}
Service layers
public interface StaffService{
List<Authority> getAuthorities();
public void saveAuthority(Authority authority);
public Staff getUserByUserName(String userName);}
#Service("staffService")
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public class StaffServiceImpl implements StaffService {
#Autowired
StaffDAO staffDAO;
private AbstractDAO<Staff> sessionFactory;
public StaffDAO getStaffDAO() {
return staffDAO;}
public void setStaffDAO(StaffDAO staffDAO) {
this.staffDAO = staffDAO;}
#Override
public List<Authority> getAuthorities() {
return staffDAO.getAuthority();}
#Override
public void saveAuthority(Authority authority) {
staffDAO.saveAuthority(authority);}
#Override
public Staff getUserByUserName(String userName) {
return staffDAO.getUserByUserName(userName);}}
CustomUserDetailsService
#Repository("customUserDetailsService")
#Service
#Component
public class CustomUserDetailsService implements UserDetailsService{
#Resource
private StaffService staffService;
public CustomUserDetailsService(){
}
public CustomUserDetailsService(StaffService staffService) {
this.staffService = staffService; }
#Override
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException {
Staff staff;
try {
staff = staffService.getUserByUserName(userName);
} catch (Exception e) {
throw new UsernameNotFoundException(
"getUserByUserName returned null.");}
return (UserDetails) staff;}}
Models
#Entity
#Table(name = "staff")
#Component
public class Staff implements Serializable, UserDetails{
private static final long serialVersionUID = 8825646974241476909L;
#Id
#Column(name = "staff_id")
private String staffId;
#Column(name = "name")
private String name;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
***** getters and setters
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
#Override
public Set<Authority> getAuthorities() {
return authorities;
}}
#Entity
#Table(name="authorities")
#Component
public class Authority implements Serializable, GrantedAuthority{
private static final long serialVersionUID = 1L;
public Authority(){
// must have one default constructor
}
#Id
#Column(name = "authority")
private String authority;
#Column(name = "role_name",nullable=false,unique=true)
private String roleName;
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
#Override
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public Authority(String authority,String roleName){
this.authority=authority;
this.roleName=roleName;
}}
XML config
<authentication-manager>
<authentication-provider user-service-ref="customUserDetailsService"/>
</authentication-manager>
<beans:bean id="customUserDetailsService"
class="com.project.professional.service.CustomUserDetailsService">
</beans:bean>
<http auto-config="true" use-expressions="true" >
<intercept-url pattern="/j_spring_security_check" access="permitAll"/>
<intercept-url pattern='/home' access="hasRole('ROLE_USER')" />
<form-login login-page='/login' always-use-default-target="true" default-target-
url="/home" authentication-failure-url="/auth/loginFailed"/>
<logout invalidate-session="true" logout-success-url='/login' />
</http>
Controller
#RequestMapping(value="/login", method = RequestMethod.GET)
public String getLoginPage(ModelMap model) {
return "login";}
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String getHomePage(Locale locale, Model model) {
return "/home";}
Jsp
<c:url value="/j_spring_security_check" var="loginUrl"/>
<form action="${loginUrl}" method="post" name="loginForm">
<p>
<label for="j_username">Username</label>
<input id="j_username" name="j_username" type="text" />
</p>
<p>
<label for="j_password">Password</label>
<input id="j_password" name="j_password" type="password" />
</p>
<input type="submit"
value="Login"/>
</form>
So what I'm asking is if there is anything that I'm missing, as to why it does not authenticate and return the home page. I would appreciate any insight into this.
Related
I have this RestController:
#RestController
#Slf4j
public class AuthenticationRestController {
#Value("${jwt.header}")
private String tokenHeader;
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private JwtTokenUtil jwtTokenUtil;
#Autowired
private UserSecurityService userSecurityService;
#Autowired
private EmailService emailService;
#PostMapping(path = "/api/v1/auth", consumes = "application/json", produces = "application/json")
public ResponseEntity<JwtAuthenticationResponse>
createAuthenticationToken( #RequestBody JwtAuthenticationRequest authenticationRequest,
HttpServletRequest request) throws AuthenticationException {
LOG.info("authenticating {} " , authenticationRequest.getUsername());
authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
...
/**
* Authenticates the user. If something is wrong, an {#link AuthenticationException} will be thrown
*/
private void authenticate(String username, String password) {
Objects.requireNonNull(username);
Objects.requireNonNull(password);
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
} catch (DisabledException e) {
e.printStackTrace();
throw new AuthenticationException("User is disabled!", e);
} catch (BadCredentialsException e) {
throw new AuthenticationException("Bad credentials!", e);
} catch (Exception e) {
e.printStackTrace();
}
}
}
but I have this error when logging:
org.springframework.security.authentication.DisabledException: User is disabled
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider$DefaultPreAuthenticationChecks.check(AbstractUserDetailsAuthenticationProvider.java:331)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:146)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:182)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:201)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.authenticate(WebSecurityConfigurerAdapter.java:518)
at com.kispackp.security.controllers.AuthenticationRestController.authenticate(AuthenticationRestController.java:138)
and
#Entity
#Table(name="t_user")
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class User implements Serializable, UserDetails {
/** The Serial Version UID for Serializable classes. */
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(unique = true)
#JsonIgnore
private String username;
#JsonIgnore
private String password;
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
}
This error happens when the user is not enabled. The interface UserDetails has a method called isEnabled, and it's checked when authenticating the user.
AbstractUserDetailsAuthenticationProvider.java
...
if (!user.isEnabled()) {
AbstractUserDetailsAuthenticationProvider.this.logger
.debug("Failed to authenticate since user account is disabled");
throw new DisabledException(AbstractUserDetailsAuthenticationProvider.this.messages
.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
}
...
You should implement it and return true in the case the user is enabled, like so:
public class User implements Serializable, UserDetails {
... your current fields and methods
#Override
public boolean isEnabled() {
return true;
}
}
I'm using thymeleaf-extras-springsecurity4 with spring security on my project. The problem is I cannot get user's extra fields (which means user information on database except username, password, enabled, etc. given by UserDetails) by using <span sec:authentication="principal.something" />.
Heres are my simple codes:
UserEntity (implements UserDetails)
#NoArgsConstructor
#AllArgsConstructor
#Getter
#Setter
#EqualsAndHashCode
#Entity
#Table(name = "users", schema = "myschema")
public class UserEntity implements UserDetails {
#Id
#GeneratedValue
#Column(name = "id", nullable = false)
private int id;
#Basic
#Column(name = "username", nullable = false, unique = true, length = 64)
private String username;
#Basic
#Column(name = "password", nullable = false, columnDefinition = "TEXT")
private String password;
#Basic
#Column(name = "enabled", nullable = false, columnDefinition = "BIT")
private boolean enabled;
#Basic
#Column(name = "phone", nullable = false, length = 16)
private String phone;
#OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
private List<AuthorityEntity> authorities;
#Override
public boolean isAccountNonExpired() {
return enabled;
}
#Override
public boolean isAccountNonLocked() {
return enabled;
}
#Override
public boolean isCredentialsNonExpired() {
return enabled;
}
#Override
public String toString() {
return username;
}
}
AuthorityEntity (implements GrantedAuthority)
#Data
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "authorities", schema = "myschema",
uniqueConstraints = #UniqueConstraint(columnNames = {"user_id", "authority"}))
public class AuthorityEntity implements GrantedAuthority {
#Id
#GeneratedValue
#Column(name = "id", nullable = false)
private int id;
#Basic
#Column(name = "authority", nullable = false, length = 24)
private String authority;
#ManyToOne
#JoinColumn(name = "user_id", referencedColumnName = "id", nullable = false)
private UserEntity user;
}
UserRepository
#Repository
public interface UserRepository extends JpaRepository<UserEntity, Integer> {
UserEntity findOneByUsernameAndEnabledTrue(String username);
}
UserService
#Service
public class UserService {
private UserRepository userRepository;
#Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public UserEntity loadUserByUsername(String username) {
return userRepository.findOneByUsernameAndEnabledTrue(username);
}
}
SecurityService (extends UserDetailService)
#Service
public class SecurityService implements UserDetailsService {
private UserService userService;
#Autowired
public SecurityService(UserService userService) {
this.userService = userService;
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDetails user = userService.loadUserByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(username);
}
return user;
}
}
SecurityConfig (extends WebSecurityConfigurerAdapter)
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private SecurityService securityService;
#Autowired
public SecurityConfig(SecurityService securityService) {
this.securityService = securityService;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/user/login").anonymous()
.antMatchers("/**").hasAnyRole("ADMIN", "USER")
.and()
.formLogin()
.loginPage("/user/login")
.defaultSuccessUrl("/")
.and()
.logout()
.logoutUrl("/user/logout")
.logoutSuccessUrl("/")
.and()
.exceptionHandling()
.accessDeniedPage("/error/403");
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
auth.userDetailsService(securityService).passwordEncoder(passwordEncoder);
}
}
index.html (using thymeleaf-extras-springsecurity)
<!DOCTYPE html>
<html lang="ko"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
layout:decorator="layout/base">
<th:block layout:fragment="content">
<h1>Main Page</h1>
<p sec:authentication="principal.username">Username</p>
<p sec:authentication="principal.phone">Phone</p>
</th:block>
The Problem
In index.html, sec:authentication="principal.username" works as expected, but sec:authentication="principal.phone" does not despite my UserDetailsService implementation stores UserEntry which implements UserDetails with extra field phone.
Questions
Is there any way to make sec:authentication="principal.phone" work well? (or "princiapl.getPhone()" respectively)
If not, can I get current user's phone number in my thymeleaf without passing it through controller?
If not, how can I pass current user's UserEntry object without plugging model explicitly for instance through mav of each controller method? Does AOP deal with this?
(Additional) In many other examples applying spring security, they don't implement UserDetails on UserEntry (or similar classes), but make a new UserDetails instance in their UserDetailService implementation like
#Override
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException {
UserInfo activeUserInfo = userInfoDAO.getActiveUser(userName);
GrantedAuthority authority = new SimpleGrantedAuthority(activeUserInfo.getRole());
UserDetails userDetails = (UserDetails)new User(activeUserInfo.getUserName(),
activeUserInfo.getPassword(), Arrays.asList(authority));
return userDetails;
}
(from here). I think my structure is not a good design but I don't know exactly why. Is there any comment for my class design?
Thanks!
If my questions are too vague, let me know so then I would update this more concrete.
In order to use additional fields contained in your user's data in Thymeleaf, you must go through the next steps.
Implement your own Spring Security's user.
Override loadUserByUsername, so that it returns your custom user.
Add the Spring Security's Thymeleaf Extras dependencies.
Use ${#authentication.getPrincipal()}, instead of sec.
STEP 1
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
// Our own implementation of the Spring Security User.
public class MyUser extends User {
// Here we add the extra fields of our users.
private String phone;
private static final long serialVersionUID = 1L;
public MyUser(String username,
String password,
Collection<GrantedAuthority> authorities,
String phone) {
super(username, password, authorities);
this.phone = phone;
}
public String getPhone() {
return realName;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
STEP 2
#Override
public MyUser loadUserByUsername(String userName)
throws AuthenticationException {
// Fetch the user.
UserDetails user = userService.loadUserByUsername(username);
// For each user's authority, add it into our authorities' collection.
Collection<GrantedAuthority> grantedAuthorities = new LinkedList<GrantedAuthority>();
if (user.getAuthorities().size() > 0){
for (Authority authority : user.getAuthorities()) {
// Add a new GrantedAuthority for each user's authorities.
grantedAuthorities.add(new SimpleGrantedAuthority(authority.getAuthority()));
}
}
return new MyUser(user.getUsername(), user.getPassword(), grantedAuthorities, user.getPhone());
}
STEP 3
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
STEP 4
<th:block th:with="auth=${#authentication.getPrincipal()}">
<p th:text="${auth ? auth.phone : 'NULL'}">Phone</p>
</th:block>
I am trying to persist data to database using spring boot - jpa - hibernate.
This is my application.properties:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/BlurAdmin
spring.datasource.username=blurAdmin
spring.datasource.password =mypassword
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
c3p0.acquireIncrement=2
c3p0.minPoolSize=10
c3p0.maxPoolSize=20
c3p0.maxIdleTime=5000
c3p0.maxStatementsPerConnection=50
c3p0.idle_test_period=30000
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update
This is HibernateConfiguration.java:
#Configuration
public class HibernateConfiguration {
#Bean
public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) {
HibernateJpaSessionFactoryBean factory = new HibernateJpaSessionFactoryBean();
factory.setEntityManagerFactory(emf);
return factory;
}
}
This is my Model: There is a warning beside #Entity saying :
The project doesn't contain persistant unit
#Entity
#Table(name = "BlurAdminUsers")
public class User implements Serializable{
public static final String ROLE_USER = "ROLE_USER";
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String username;
private String email;
private String password;
private String role;
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
protected User(){
}
public User(String username,String email,String password){
this.username = username;
this.password = password;
this.email = email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
This is Repository:
#Transactional
public interface UsersRepository extends JpaRepository<User, Long> {
List<User> findByEmail(String email);
List<User> findByUsername(String username);
}
This is my aop class where I am trying to persist data:
#Component
public class Signup {
private DataValidation dataValidation;
private Message message;
private UsersRepository repository;
#Autowired
public Signup(UsersRepository repository) {
dataValidation = new DataValidation();
this.repository = repository;
}
#Around("execution(* com.ghewareunigps.vts.ui.web.controllers.SignupController.signup(..)) && args(user,..)")
public Message validateAndSignup(ProceedingJoinPoint joinPoint, User user) throws Throwable {
List<User> usersWithEmail = repository.findByEmail(user.getEmail());
List<User> usersWithUsername = repository.findByUsername(user.getUsername()) ;
user.setRole(Roles.ROLE_USER);
if (dataValidation.validate(user.getUsername(), user.getEmail(), user.getPassword())) {
if(usersWithEmail.isEmpty() && usersWithUsername.isEmpty()){
message = (Message) joinPoint.proceed();
try{
repository.save(user);
}catch(Exception ex){
System.out.println(ex);
}
}
else{
message = new Message(false,"Sorry user with email or username already exists");
}
} else {
message = new Message(false, " please recheck your credentials");
}
return message;
}
}
There's no exceptions being thrown and I have added all the dependencies. Can some please tell me where I am going wrong?
I´m using spring-security to validate at users in function its profiles, but my app doesn´t make it well, when I see the file log, it show me this:
DEBUG DaoAuthenticationProvider:308 - User account is locked
In my form login I put the data well, but I never pass to other page, I´m always in the same page (form page), I introduce good or bad data
My code is:
file configuration spring-security.xml
<beans:beans xmlns:security="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<security:http auto-config="true" access-decision-manager-ref="accessDecisionManager">
<security:intercept-url pattern="/" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/init" access="PROFILE_ADMINISTRATOR" />
<security:form-login
login-page="/"
default-target-url="/init"
always-use-default-target='true'
authentication-failure-url="/"/>
<security:http-basic />
</security:http>
<security:authentication-manager alias="autenticationManagerUserService">
<security:authentication-provider user-service-ref="userService">
<security:password-encoder hash="md5"/>
</security:authentication-provider>
</security:authentication-manager>
<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<beans:property name="decisionVoters">
<beans:list>
<beans:ref bean="decisorDeRoles"/>
<beans:ref bean="decisorDeAutenticacion"/>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="decisorDeRoles" class="org.springframework.security.access.vote.RoleVoter">
<beans:property name="rolePrefix" value="PROFILE_"/>
</beans:bean>
<beans:bean id="decisorDeAutenticacion" class="org.springframework.security.access.vote.AuthenticatedVoter"/>
<beans:bean id="loggerListener" class="org.springframework.security.authentication.event.LoggerListener"/>
</beans:beans>
class of UserDatailsService
#Service("userService")
public class SecurityAuthenticationProvider implements UserDetailsService
{
UserDao userDao = new UserDao ();
#Override
public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException, DataAccessException
{
User user = null;
List<User> users = userDao.getUser (username);
if (users.size () == 0)
{
throw new UsernameNotFoundException ("");
}
else
{
user = users.get (0);
user.setAuthorities (userDao.getProfileUser (username));
return user;
}
}
}
class UserDatails
public class User implements UserDetails
{
private List<GrantedAuthority> profiles;
private String username;
private String password;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
private boolean enabled;
#Override
public Collection<? extends GrantedAuthority> getAuthorities ()
{
return profiles;
}
#SuppressWarnings("unchecked")
public void setAuthorities (List<? extends GrantedAuthority> profiles)
{
this.profiles = (List<GrantedAuthority>) profiles;
}
#Override
public String getPassword ()
{
return password;
}
#Override
public String getUsername ()
{
return username;
}
#Override
public boolean isAccountNonExpired ()
{
return accountNonExpired;
}
#Override
public boolean isAccountNonLocked ()
{
return accountNonLocked;
}
#Override
public boolean isCredentialsNonExpired ()
{
return credentialsNonExpired;
}
#Override
public boolean isEnabled ()
{
return enabled;
}
public void setUsername (String username)
{
this.username = username;
}
public void setPassword (String password)
{
this.password = password;
}
public void setAccountNonExpired (boolean accountNonExpired)
{
this.accountNonExpired = accountNonExpired;
}
public void setAccountNonLocked (boolean accountNonLocked)
{
this.accountNonLocked = accountNonLocked;
}
public void setCredentialsNonExpired (boolean credentialsNonExpired)
{
this.credentialsNonExpired = credentialsNonExpired;
}
public void setEnabled (boolean enabled)
{
this.enabled = enabled;
}
}
class GrantedAuthority
public class Profile implements GrantedAuthority
{
private String profile;
#Override
public String getAuthority ()
{
return profile;
}
public String getProfile ()
{
return profile;
}
public void setProfile (String profile)
{
this.profile = profile;
}
}
Class that I have created to simulate access to database (to obtain data)
public class UserDao
{
public List<? extends GrantedAuthority> getProfileUser (String name)
{
List<GrantedAuthority> listGrantedAuthorities = new ArrayList<GrantedAuthority> ();
Profile profile = new Profile ();
profile.setProfile ("PROFILE_ADMINISTRATOR");
listGrantedAuthorities.add (profile);
return listGrantedAuthorities;
}
public List<User> getUser (String name)
{
List<User> listUser = new ArrayList<User> ();
User user = new User ();
user.setUsername ("Admin");
user.setPassword ("1234");
// user.setAccountNonExpired (true);
// user.setAccountNonLocked (true);
// user.setCredentialsNonExpired (true);
// user.setEnabled (true);
listUser.add (user);
return listUser;
}
}
Thanks.
I faced the same issue while working with rest oauth2 spring security.
SOLUTION
you need to make few changes in your class which implements UserDetails (org.springframework.security.core.userdetails), in your case its the user class.
For the following overriding methods isAccountNonLocked(), isAccountNonExpired(), isEnabled(), isCredentialsNonExpired()
change the retrun type to true (by default its false).
make note that these all methods should have a logic to return true or false depending on your requirement but to make your code work i am suggesting you to return true for all the mentioned methods.
I have the following 2 objects: User and DomainUser
User.java:
package com.domain;
import java.io.Serializable;
#SuppressWarnings("serial")
public class User implements Serializable {
private long id = 0;
private String userName;
private String password;
public User() {
}
public User(long id) {
this.id = id;
}
public String toString() {
StringBuffer sb = new StringBuffer(256);
sb.append("[id : ").append(id).append(", ");
sb.append("userName : ").append(userName).append(", ");
sb.append("password : ").append(password).append("]");
return sb.toString();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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;
}
}
DomainUser.java
package com.domain;
import org.springframework.beans.factory.annotation.Autowired;
public class DomainUser {
#Autowired
private User user;
private String domainName;
public String toString() {
StringBuffer sb = new StringBuffer(255);
sb.append(user.toString()).append(", domainName : ").append(domainName);
return sb.toString();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
}
I am trying to autowire the User object in to DomainUser by using #Autowired annotation. But when i run the test as below, the User object is not populated.
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-3.0.xsd">
<bean id="user" class="com.domain.User">
<constructor-arg value="#{1234}"/>
<property name="userName" value="somename" />
<property name="password" value="sompassword" />
</bean>
<bean id="domainUser" class="com.domain.DomainUser">
<property name="domainName" value="mysite" />
</bean>
</beans>
DomainUserTest.java
package com.domain.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.domain.DomainUser;
public class DomainUserTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
DomainUser domainUser = (DomainUser) context.getBean("domainUser");
System.out.println(domainUser.toString());
}
}
If I autowire using the 'byType' in the autowiring attribute in the applicationContext.xml it works fine :
<bean id="domainUser" class="com.domain.DomainUser" autowire="byType">
<property name="domainName" value="mysite" />
</bean>
Can some one help me understand why doesnt #Autowired annotation produce the same result?
You need an AutowiredAnnotationBeanPostProcessor to handle the injection of #Autowired properties. You could place <context:annotation-config /> (you need to define the context-namespace in your xml) or just define the post processor as a bean in your xml:
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
See for example here for details.