2015-09-07 113 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