Forked from danpolites/BCryptSearchModeSearchDatabaseAuthenticationHandler.java
Created
November 22, 2013 23:56
-
-
Save ukasiu/7608906 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials; | |
import org.springframework.security.crypto.bcrypt.BCrypt; | |
import org.springframework.beans.factory.InitializingBean; | |
import org.jasig.cas.adaptors.jdbc.AbstractJdbcUsernamePasswordAuthenticationHandler; | |
/** | |
* Class that given a table, username field and password field will query a | |
* database table to see if the user exists. If the user exists, the | |
* encrypted password, from the datbase, will be compared to the plain | |
* text password, from the credentials, by using the BCrypt tools. | |
*/ | |
public class BCryptSearchModeSearchDatabaseAuthenticationHandler extends | |
AbstractJdbcUsernamePasswordAuthenticationHandler implements InitializingBean { | |
private String fieldUser; | |
private String fieldPassword; | |
private String tableUsers; | |
private String sql; | |
public boolean authenticateUsernamePasswordInternal(UsernamePasswordCredentials credentials) { | |
final String username = getPrincipalNameTransformer().transform(credentials.getUsername()); | |
final String plainTextPassword = credentials.getPassword(); | |
final String encryptedPassword = getJdbcTemplate().queryForObject(sql, String.class, username); | |
return isPasswordValid(plainTextPassword, encryptedPassword); | |
} | |
public void afterPropertiesSet() throws Exception { | |
sql = "select " + fieldPassword + " from " + | |
tableUsers + " where " + fieldUser + " = ?"; | |
} | |
private boolean isPasswordValid(String plainTextPassword, String encryptedPassword) { | |
if(plainTextPassword == null || plainTextPassword.trim().length() == 0 || | |
encryptedPassword == null || encryptedPassword.trim().length() == 0) { | |
return false; | |
} | |
return BCrypt.checkpw(plainTextPassword, encryptedPassword); | |
} | |
/** | |
* @param fieldPassword The name of the encrypted password field. | |
*/ | |
public final void setFieldPassword(final String fieldPassword) { | |
this.fieldPassword = fieldPassword; | |
} | |
/** | |
* @param fieldUser The name of the username field. | |
*/ | |
public final void setFieldUser(final String fieldUser) { | |
this.fieldUser = fieldUser; | |
} | |
/** | |
* @param tableUsers The name of the table holding the user information. | |
*/ | |
public final void setTableUsers(final String tableUsers) { | |
this.tableUsers = tableUsers; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment