您好,欢迎访问一九零五行业门户网

Cas(06)基于数据库的认证

基于数据库的认证 cas server自身已经为我们实现了几种基于jdbc的authenticationhandler实现,但它们不包含在cas server的核心包里面,而是包含在cas-server-support-jdbc中,如果我们要使用cas server已经实现好的基于jdbc的authenticationhandler,我们必
基于数据库的认证
cas server自身已经为我们实现了几种基于jdbc的authenticationhandler实现,但它们不包含在cas server的核心包里面,而是包含在cas-server-support-jdbc中,如果我们要使用cas server已经实现好的基于jdbc的authenticationhandler,我们必须先将cas-server-support-jdbc对应的jar包、相关数据库的驱动,以及所需要使用的数据源实现等jar包加入cas server的类路径中。如果是基于maven的war覆盖机制来修改cas server的配置文件,则我们可以在自己的maven项目的依赖中加入如下项(对应的驱动就没贴出来了)。
      dependency>
         groupid>org.jasig.casgroupid>
         artifactid>cas-server-support-jdbcartifactid>
         version>${cas.version}version>
         scope>runtimescope>
      dependency>
cas server默认已经实现好的基于jdbc的authenticationhandler有三个,它们都继承自abstractjdbcusernamepasswordauthenticationhandler,而且在认证过程中都需要一个datasource。下面来对它们做一个简要的介绍。
1.1     bindmodesearchdatabaseauthenticationhandler       bindmodesearchdatabaseauthenticationhandler将试图以传入的用户名和密码从配置的datasource中建立一个连接,如果连接成功,则表示认证成功,否则就是认证失败。以下是bindmodesearchdatabaseauthenticationhandler源码的一段主要代码,通过它我们可以明显的看清其逻辑:
    protected final boolean authenticateusernamepasswordinternal(
        final usernamepasswordcredentials credentials)
        throws authenticationexception {
        final string username = credentials.getusername();
        final string password = credentials.getpassword();
try {
            final connection c = this.getdatasource()
                .getconnection(username, password);
            datasourceutils.releaseconnection(c, this.getdatasource());
            returntrue;
        } catch (final sqlexception e) {
            returnfalse;
        }
    }
当然,这种实现也需要你的datasource支持getconnection(user,password)才行,否则将返回false。dbcp的basicdatasource的不支持的,而c3p0的combopooleddatasource支持。
       以下是一个使用bindmodesearchdatabaseauthenticationhandler的配置示例:
   bean id=authenticationmanager
      class=org.jasig.cas.authentication.authenticationmanagerimpl>
      ...
      property name=authenticationhandlers>
         list>
            ...
            beanclass=org.jasig.cas.adaptors.jdbc.bindmodesearchdatabaseauthenticationhandler>
                property name=datasource ref=datasource/>
            bean>
            ...
         list>
      property>
      ...
   bean>
1.2     querydatabaseauthenticationhandler       使用querydatabaseauthenticationhandler需要我们指定一个sql,该sql将接收一个用户名作为查询条件,然后返回对应的密码。该sql将被querydatabaseauthenticationhandler用来通过传入的用户名查询对应的密码,如果存在则将查询的密码与查询出来的密码进行匹配,匹配结果将作为认证结果。如果对应的用户名不存在也将返回false。
       以下是querydatabaseauthenticationhandler的一段主要代码:
    protected final boolean authenticateusernamepasswordinternal(finalusernamepasswordcredentials credentials) throws authenticationexception {
        final string username = getprincipalnametransformer().transform(credentials.getusername());
        final string password = credentials.getpassword();
        final string encryptedpassword = this.getpasswordencoder().encode(
            password);
try {
            final string dbpassword = getjdbctemplate().queryforobject(this.sql, string.class, username);
            return dbpassword.equals(encryptedpassword);
        } catch (final incorrectresultsizedataaccessexception e) {
            // this means the username was not found.
            returnfalse;
        }
    }
上面的逻辑非常明显。此外,如你所见,querydatabaseauthenticationhandler使用的用户名会经过principalnametransformer进行转换,而密码会经过passwordencoder进行编码。cas server中基于jdbc的authenticationhandler实现中使用到的principalnametransformer默认是不进行任何转换的noopprincipalnametransformer,而默认使用的passwordencoder也是不会经过任何编码的plaintextpasswordencoder。当然了,cas-server-jdbc-support对它们也有另外两种支持,即prefixsuffixprincipalnametransformer和defaultpasswordencoder。
1.2.1  prefixsuffixprincipalnametransformer       prefixsuffixprincipalnametransformer的作用很明显,如其名称所描述的那样,其在转换时会将用户名加上指定的前缀和后缀。所以用户在使用的时候需要指定prefix和suffix两个属性,默认是空。
1.2.2  defaultpasswordencoder       defaultpasswordencoder底层使用的是标准java类库中的messagedigest进行加密的,其支持md5、sha等加密算法。在使用时需要通过构造参数encodingalgorithm来指定使用的加密算法,可以使用characterencoding属性注入来指定获取字节时使用的编码,不指定则使用默认编码。以下是defaultpasswordencoder的源码,其展示了defaultpasswordencoder的加密逻辑。
public final class defaultpasswordencoder implements passwordencoder {
privatestaticfinalchar[] hex_digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8','9', 'a', 'b', 'c', 'd', 'e', 'f'};
@notnull
    privatefinal string encodingalgorithm;
private string characterencoding;
public defaultpasswordencoder(final string encodingalgorithm) {
        this.encodingalgorithm = encodingalgorithm;
    }
public string encode(final string password) {
        if (password == null) {
            returnnull;
        }
try {
            messagedigest messagedigest = messagedigest
                .getinstance(this.encodingalgorithm);
if (stringutils.hastext(this.characterencoding)) {
                messagedigest.update(password.getbytes(this.characterencoding));
            } else {
                messagedigest.update(password.getbytes());
            }
finalbyte[] digest = messagedigest.digest();
return getformattedtext(digest);
        } catch (final nosuchalgorithmexception e) {
            thrownew securityexception(e);
        } catch (final unsupportedencodingexception e) {
            thrownew runtimeexception(e);
        }
    }
/**
     * takes the raw bytes from the digest and formats them correct.
     *
     * @param bytes the raw bytes from the digest.
     * @return the formatted bytes.
     */
    private string getformattedtext(byte[] bytes) {
        final stringbuilder buf = new stringbuilder(bytes.length * 2);
for (int j = 0; j length; j++) {
            buf.append(hex_digits[(bytes[j] >> 4) & 0x0f]);
            buf.append(hex_digits[bytes[j] & 0x0f]);
        }
        return buf.tostring();
    }
publicfinalvoid setcharacterencoding(final string characterencoding) {
        this.characterencoding = characterencoding;
    }
}
如果在认证时需要使用defaultpasswordencoder,则需要确保数据库中保存的密码的加密方式和defaultpasswordencoder的加密算法及逻辑是一致的。如果这些都不能满足你的需求,则用户可以实现自己的principalnametransformer和passwordencoder。
以下是一个配置使用querydatabaseauthenticationhandler进行认证,且使用defaultpasswordencoder对密码进行md5加密的示例:
   bean id=authenticationmanager
      class=org.jasig.cas.authentication.authenticationmanagerimpl>
      ...
      property name=authenticationhandlers>
         list>
            ...
            beanclass=org.jasig.cas.adaptors.jdbc.querydatabaseauthenticationhandler>
                property name=datasource ref=datasource/>
                property name=passwordencoder ref=passwordencoder/>
                property name=sql value=select password from t_user where username = ?/>
            bean>
            ...
         list>
      property>
      ...
   bean>
bean id=passwordencoderclass=org.jasig.cas.authentication.handler.defaultpasswordencoder>
      constructor-arg value=md5/>
   bean>
1.3     searchmodesearchdatabaseauthenticationhandler       searchmodesearchdatabaseauthenticationhandler的主要逻辑是将传入的用户名和密码作为条件从指定的表中进行查询,如果对应记录存在则表示认证通过。使用该authenticationhandler时需要我们指定查询时使用的表名(tableusers)、用户名对应的字段名(fielduser)和密码对应的字段名(fieldpassword)。此外,还可以选择性的使用principalnametransformer和passwordencoder。以下是searchmodesearchdatabaseauthenticationhandler源码中的一段主要代码:
private static final string sql_prefix = select count('x') from ;
@notnull
    private string fielduser;
@notnull
    private string fieldpassword;
@notnull
    private string tableusers;
private string sql;
protectedfinalboolean authenticateusernamepasswordinternal(finalusernamepasswordcredentials credentials) throws authenticationexception {
        final string transformedusername = getprincipalnametransformer().transform(credentials.getusername());
        final string encyptedpassword = getpasswordencoder().encode(credentials.getpassword());
finalint count = getjdbctemplate().queryforint(this.sql,
           transformedusername, encyptedpassword);
return count > 0;
    }
publicvoid afterpropertiesset() throws exception {
        this.sql = sql_prefix + this.tableusers +  where  + this.fielduser
        +  = ? and  + this.fieldpassword +  = ?;
    }
以下是一个使用searchmodesearchdatabaseauthenticationhandler的配置示例:
bean id=authenticationmanager
      class=org.jasig.cas.authentication.authenticationmanagerimpl>
      ...
      property name=authenticationhandlers>
         list>
            ...
            beanclass=org.jasig.cas.adaptors.jdbc.searchmodesearchdatabaseauthenticationhandler>
                property name=datasource ref=datasource/>
                property name=passwordencoder ref=passwordencoder/>
                property name=tableusers value=t_user/>
                property name=fielduser value=username/>
                property name=fieldpassword value=password/>
            bean>
            ...
         list>
      property>
      ...
   bean>
至此,cas-server-support-jdbc中支持jdbc的三个authenticationhandler就讲完了。如果用户觉得它们都不能满足你的要求,则还可以选择使用自己实现的authenticationhandler。至于其它认证方式,请参考官方文档。
(注:本文是基于cas 3.5.2所写)
http://blog.csdn.net/elim168/article/details/44420293)
其它类似信息

推荐信息