Spring安全身份验证忽略密码

时间:2015-09-07 04:44:16

标签: spring authentication spring-security

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

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;
}

2 个答案:

答案 0 :(得分:0)

您应该可以完成此操作,创建自定义AuthenticationProvider实施,并配置您的AuthenticationManager以使用它。

答案 1 :(得分:0)

您应该创建一个Custom Filter到期。 Filter应扩展类AbstractAuthenticationProcessingFilter并返回Custom Authentication个对象。然后Authentication Provider会看到它,并且只检查Filter返回的用户名。完成所有操作后,必须将Filter配置为Spring Security上下文才能使其正常工作。

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