我有一个用户bean,其中包含userName,profileName,email等字段。
我正在我的应用程序中实现Spring Security。在登录表单中,我希望用户输入profileName或email&他应该能够同时登录。但似乎配置仅适用于userName。我使用hibernate从数据库中获取用户详细信息。 以下是我的代码
FormLogin.jsp
<form name='f' action="<c:url value='j_spring_security_check' />"
method='POST'>
<table>
<tr>
<td>Email/ProfileName</td>
<td><input type='text' name='j_username' value=''>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password' />
</td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"
value="submit" />
</td>
</tr>
<tr>
<td colspan='2'><input name="reset" type="reset" />
</td>
</tr>
</table>
</form>
CustomUserDetailsService类中的loadByUserName方法
public UserDetails loadUserByUsername(String name)throws UsernameNotFoundException, DataAccessException
{
//returns the get(0) of the user list obtained from the db
User domainUser = userDAO.getUser(name);
logger.info("User fetched from database in loadUserByUsername method " + domainUser);
Set<Roles> roles = domainUser.getRole();
logger.info("roles of the user"+ roles);
Set<GrantedAuthority> authorities = new HashSet<>();
for(Roles role:roles) {
authorities.add(new SimpleGrantedAuthority(role.getRole()));
logger.info("role" +role+" role.getRole()"+(role.getRole()));
}
return new org.springframework.security.core.userdetails.User(
domainUser.getName(),
domainUser.getPassword(),
domainUser.isEnabled(),
domainUser.isAccountNonExpired(),
domainUser.isCredentialsNonExpired(),
domainUser.isAccountNonLocked(),
authorities);
}
从db
查询@SuppressWarnings("unchecked")
public User getUser(String name){
List<User> userList = new ArrayList<User>();
Query query = sessionFactory.getCurrentSession().createQuery("from User u where u.name = :name");
query.setParameter("name", name);
userList = query.list();
if (userList.size() > 0)
return userList.get(0);
else
return null;
}
任何人都可以帮忙解决这个问题吗?
弹簧security.xml文件
<http auto-config="true">
<intercept-url pattern="/forms/welcome*" access="ROLE_ADMIN" />
<!-- Below config will display the custom form for authentication -->
<form-login login-page="/forms/login" default-target-url="/forms/welcome"
authentication-failure-url="/forms/loginfailed" />
<logout logout-success-url="/forms/logout" />
<!-- <http-basic /> -->
</http>
<authentication-manager>
<authentication-provider user-service-ref="myUserDetailService">
</authentication-provider>
</authentication-manager>
答案 0 :(得分:3)
您不发布安全配置。我假设您已经设置了DaoAuthenticationProvider
的标准配置,并且您已经能够使用用户名登录。
我这个特例我只看到一个修改,允许用户名或电子邮件登录。向您的hibernate查询添加or
谓词,该查询也通过电子邮件查询用户。我假设您的实体有一个属性email
。
"from User u where u.name = :name or u.email = :name"