Skip to content

Commit de622d1

Browse files
Shenker93rwinch
authored andcommitted
Improve JdbcUserDetailsManager.userExists method
1 parent 47f7d83 commit de622d1

File tree

2 files changed

+12
-6
lines changed

2 files changed

+12
-6
lines changed

core/src/main/java/org/springframework/security/provisioning/JdbcUserDetailsManager.java

+7-6
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
7777

7878
public static final String DEF_DELETE_USER_AUTHORITIES_SQL = "delete from authorities where username = ?";
7979

80-
public static final String DEF_USER_EXISTS_SQL = "select username from users where username = ?";
80+
public static final String DEF_USER_EXISTS_SQL = "select count(*) from users where username = ?";
8181

8282
public static final String DEF_CHANGE_PASSWORD_SQL = "update users set password = ? where username = ?";
8383

@@ -337,12 +337,13 @@ protected Authentication createNewAuthentication(Authentication currentAuth, Str
337337

338338
@Override
339339
public boolean userExists(String username) {
340-
List<String> users = requireJdbcTemplate().queryForList(this.userExistsSql, String.class, username);
341-
if (users.size() > 1) {
342-
throw new IncorrectResultSizeDataAccessException("More than one user found with name '" + username + "'",
343-
1);
340+
@SuppressWarnings("ConstantConditions")
341+
int usersCount = getJdbcTemplate().queryForObject(this.userExistsSql, Integer.class, username);
342+
if (usersCount > 1) {
343+
throw new IncorrectResultSizeDataAccessException(
344+
"[" + usersCount + "] users found with name '" + username + "', expected 1", 1);
344345
}
345-
return users.size() == 1;
346+
return usersCount == 1;
346347
}
347348

348349
@Override

core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java

+5
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,11 @@ public void userExistsReturnsFalseForNonExistentUsername() {
189189
assertThat(this.manager.userExists("joe")).isFalse();
190190
}
191191

192+
@Test
193+
public void userExistsReturnsFalseForNullUsername() {
194+
assertThat(this.manager.userExists(null)).isFalse();
195+
}
196+
192197
@Test
193198
public void userExistsReturnsTrueForExistingUsername() {
194199
insertJoe();

0 commit comments

Comments
 (0)