我正在尝试实现一个功能,用户可以通过userid或电子邮件地址登录。为了实现这一点,我实现了自己的UserDetailsService并覆盖了loadUserByUsername方法。
我面临的问题是每当我尝试进行身份验证时,都会调用loadUserByUsername方法两次。我是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;
}
}
日志输出 -
在loadUserByUsername中:testuser@test.com
在loadUserByUsername:testuser@test.com
为了便于理解,我有硬编码的用户名和密码值。