接着上一篇内容介绍,自定义密码验证
加密的类
加密的类,必须实现org.springframework.security.crypto.password.PasswordEncoder
,因为验证的时候,cas就是调用接口,然后验证是否正确
package com.tingfeng; import org.springframework.security.crypto.password.PasswordEncoder; import java.math.BigInteger; import java.security.MessageDigest; /** * 自定义加密类 */ public class CustomPasswordEncoder implements PasswordEncoder { public String encode(CharSequence password) { try { //给数据进行md5加密 MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.toString().getBytes()); String pwd = new BigInteger(1, md.digest()).toString(16); System.out.println("encode方法:加密前(" + password + "),加密后(" + pwd + ")"); return pwd; } catch (Exception e) { return null; } } /** * 调用这个方法来判断密码是否匹配 */ @Override public boolean matches(CharSequence rawPassword, String encodePassword) { // 判断密码是否存在 if (rawPassword == null) { return false; } //通过md5加密后的密码 String pass = this.encode(rawPassword.toString()); System.out.println("matches方法:rawPassword:" + rawPassword + ",encodePassword:" + encodePassword + ",pass:" + pass); //比较密码是否相等的问题 return pass.equals(encodePassword); } }
注册加密的类
编辑application.properties 文件,采用MD5加密
## # CAS Authentication Credentials # # cas.authn.accept.users=tingfeng::tingfeng ## # Query Database Authentication 数据库查询校验用户名开始 # # 查询账号密码sql,必须包含密码字段 cas.authn.jdbc.query[0].sql=select * from sys_user where username=? cas.authn.jdbc.query[0].fieldPassword=password cas.authn.jdbc.query[0].fieldExpired=expired cas.authn.jdbc.query[0].fieldDisabled=disabled cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/cas_sso_record?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false cas.authn.jdbc.query[0].user=casuser cas.authn.jdbc.query[0].password=casuser #默认加密策略,通过encodingAlgorithm来指定算法,默认NONE不加密 cas.authn.jdbc.query[0].passwordEncoder.type=com.tingfeng.CustomPasswordEncoder cas.authn.jdbc.query[0].passwordEncoder.characterEncoding=UTF-8 cas.authn.jdbc.query[0].passwordEncoder.encodingAlgorithm=MD5
三、测试
四、我的源码
https://github.com/X-rapido/CAS_SSO_Record