I am trying to implement a feature where users can login either by userid or by email address. In order to achieve this I am implementing my own UserDetailsService and overriding loadUserByUsername method.
The problem I am facing is that the method loadUserByUsername is called twice whenever I am trying to authenticate. I am new to spring framework and am finding it difficult to trace why is this happening. Appreciate if someone can point me to the right direction to fix this.
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<http auto-config="true" use-expressions="true">
<csrf disabled="true"/>
<form-login login-processing-url="/login" login-page='/showlogin' default-target-url='/' authentication-failure-url='/authentication-failure' />
<intercept-url pattern="/secureview/**" access="hasRole('ROLE_USER')" />
<remember-me key="patternMinder"/>
<logout logout-url="/logout" logout-success-url="/?logout" />
</http>
<beans:bean id='userDetailsService' class='com.pmz.charting.security.UserDetailServiceImpl'>
</beans:bean>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsService" >
</authentication-provider>
</authentication-manager>
</beans:beans>
UserDetailServiceImpl:
public class UserDetailServiceImpl implements UserDetailsService{
@Override
public UserDetails loadUserByUsername(String user) throws UsernameNotFoundException {
System.out.println("In loadUserByUsername:" + user);
return buildUserFromUserEntity();
}
private UserDetails buildUserFromUserEntity() {
// convert model user to spring security user
String username = "testuser@test.com";
String password = "testuser";
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
UserDetails springUser = new User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
return springUser;
}
}
Output in logs -
In loadUserByUsername:testuser@test.com
In loadUserByUsername:testuser@test.com
For ease of understanding I have hard coded userid and password values.