CAS(Central Authentication Service)是一款由Yale大學開發的單點登錄系統,其主要功能是集中管理多個應用系統的用戶身份驗證和鑒權。CAS通過一次登錄即可訪問多個應用系統,在保障安全的同時提高了用戶體驗。CAS源碼中支持的數據庫種類有許多,其中包括MySQL。
public class JdbcPasswordHandler extends AbstractPasswordHandler {
private static final String ALGORITHM = "SHA1";
private static final String MY_SQL_ALGORITHM = "{SHA1}";
private String algorithm = ALGORITHM;
private String mysqlAlgorithm = MY_SQL_ALGORITHM;
private String dataSource;
public JdbcPasswordHandler() {
super();
}
public void setAlgorithm(final String algorithm) {
this.algorithm = algorithm;
}
public void setMysqlAlgorithm(final String algorithm) {
this.mysqlAlgorithm = algorithm;
}
public void setDataSource(final String dataSource) {
this.dataSource = dataSource;
}
@Override
public boolean matches(final String passwordToCheck,
final String storedPassword) {
try (val conn = getConnection(dataSource)) {
val digestPsw = encode(passwordToCheck);
val statement = conn.prepareStatement(getSql(storedPassword));
statement.setString(1, digestPsw);
statement.setString(2, storedPassword);
val resultset = statement.executeQuery();
return resultset.next();
} catch (final Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@Override
protected String encode(final String password) {
try {
return "{" + algorithm + "}" + DigestUtils.sha1Hex(password);
} catch (final Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
private String getSql(final String password) {
val mysqlPsw = StringUtils.startsWith(password, mysqlAlgorithm);
val sql = new StringBuilder("SELECT id FROM ")
.append("users ")
.append("WHERE username = ? ");
if (mysqlPsw) {
sql.append(" AND password = ? ");
} else {
sql.append(" AND password = ? ");
}
return sql.toString();
}
private Connection getConnection(final String datasource) {
try {
val ctx = new InitialContext();
val ds = (DataSource) ctx.lookup(datasource);
return ds.getConnection();
} catch (final Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
以上是CAS源碼中與MySQL相關的JdbcPasswordHandler類。在該類中,通過傳遞數據源地址,實現了密碼校驗的功能。其中,encode()方法用于加密密碼,matches()方法用于校驗密碼,getConnection()方法用于獲取數據庫連接。