2015-09-07 103 views
1

在我的项目中,我实现了Spring Security。它检查用户名和密码是否正确。我只想验证用户名,而不是密码。我怎样才能做到这一点?Spring安全认证忽略密码

public UserDetails loadUserByUsername(String username) { 
    if (lan == null) { 
    // loadPasswordRules(); 
    } 

    List<UserDetails> users = loadUsersByUsername(username); 
    if (users.size() == 0) { 
     throw new AuthenticationServiceException("Username " + username + " is invalid "); 
    } 

    UserDetails user = users.get(0); // contains no IRole[] 
    /** Raising exception since start and expiry of user is not valid. */ 
    /** Raising exception since start and expiry of user is not valid. */ 
    Date todayDate = new Date(); 
    if (!((todayDate).after(((User) user).getStartDate()) && (todayDate).before(((User) user).getExpiryDate()))) { 
     throw new AuthenticationServiceException("User " + username + " account is expired."); 
     /* throw new LockedException("User " + username + " account is expired."); 
      throw new UsernameNotFoundException("User {" + username + "} account is expired."); SPRING_SECURITY_LAST_EXCEPTION.message */ 
    } 

    /*if (((User) user).getLastSuccessLogin() != null) { 
     Calendar newDate = Calendar.getInstance(); 
     newDate.setTime(todayDate); 
     newDate.add(Calendar.DAY_OF_YEAR, - lan.intValue()); 
     Calendar oldDate = Calendar.getInstance(); 
     oldDate.setTime(((User) user).getLastSuccessLogin()); 
     if (newDate.after(oldDate)) { 
      lockUserAccount(username); 
      throw new AuthenticationServiceException("User " + username + " account is expired."); 
     } 
    }*/ 

    Set<IRole> dbAuthsSet = new HashSet<IRole>(); 
    if (enableAuthorities) { 
     dbAuthsSet.addAll(loadUserAuthorities(user.getUsername())); 
    } 
    List<IRole> dbAuths = new ArrayList<IRole>(dbAuthsSet); 
    if (dbAuths.size() == 0) { 
     throw new AuthenticationServiceException("Username " + username + " has no assigned roles."); 
    } 
    ((User) user).setRoles(dbAuths); 
    return user; 
} 

回答

0

你应该能够做到这一点创建一个自定义AuthenticationProvider实施和配置您的AuthenticationManager使用的。

0

您应该创建一个Custom Filter到此为止。 Filter应扩展类AbstractAuthenticationProcessingFilter并返回Custom Authentication对象。那么Authentication Provider将会看到它,并且只检查由Filter返回的用户名。完成所有工作后,您必须将Spring配置Filter以使其可用。

您还可以在这里看到我的完整示例:http://phuonghuynh.github.io/java/spring/security/2015/09/06/spring-security-multiple-authentication-providers.html