Apereo CAS 之 用户认证
上篇使用默认的用户名密码登录 casuser/Mellon 登录 cas。我们可以通过 etc/cas/config/cas.properties 配置不同的后端存储用来进行用户信息的 authentication 的校验。
这里使用 MongoDB 作为用户信息认证的后端存储,参考这里官方文档:https://apereo.github.io/cas/6.5.x/authentication/MongoDb-Authentication.html。
主要是三个步骤,但需要先把 cas-server-support-mongo 加到 build.gradle 文件。
implementation "org.apereo.cas:cas-server-support-mongo"
1)在 MongoDb 中保存用户信息
获得密码’md5password’的 MD5 值,并保存到 collection。
$ md5 -s ‘md5password’
MD5 (“md5password”) = ec85070aa70e598eda72cbe82d99fabc
db.cas_user.insert({
"username": "casuser",
"password": "ec85070aa70e598eda72cbe82d99fabc",
"first_name": "john",
"last_name": "smith"
})
2) 配置 cas 从 MongoDB 获取用户信息
通过直接设置 client-uri 表明连接到 mongoDB 的哪个库做认证,就不用再分别设置注入 host、database 这样的参数了。cas-user
是保存用户数据的 collection。
如果因为我们使用 MD5 作为密码摘要来验证,所以这里 password-encoder.type 设置为 DEFAULT,encoding-algorithm 设置为 MD5。可以查看源码 DefaultPasswordEncoder 理解这个设置,诸如 BCrypt 是不需要 encoding-algorithm 的。
cas 也支持 BCRYPT、PBKDF2 这样的密码编码。也可以把 type 设置为一个自己实现的 PasswordEncoder。
如果密码是明文保存的,则可把 password-encoder.type 设为 NONE。
# -- Use MongoDB as the authentication data source.
cas.authn.mongo.client-uri=mongodb://admin:password@localhost:27017/center0
cas.authn.mongo.collection=cas_user
# cas.authn.mongo.database-name=
# cas.authn.mongo.host=localhost=
# cas.authn.mongo.password=
# cas.authn.mongo.port=27017
# cas.authn.mongo.principal-transformation.groovy.location=
# cas.authn.mongo.user-id=
cas.authn.mongo.password-encoder.type=DEFAULT
cas.authn.mongo.password-encoder.encoding-algorithm=MD5
3)登录验证
运行./gradlew clean copyCasConfiguration build run
,在浏览器输入 casuser / md5password 进行登录。
4)使用 BCrypt
BCrypt 是当前最通用的 password encoding 方式了。BCrypt 会自己内部产生一个随机 salt 并和 hash 的结果保存在一起作为 encode 的结果。这样每次做 BCrypt 的结果都不同并且再校验时也无需提供 salt。可参考这篇文章spring-security-registration-password-encoding-bcrypt。
生成一个密码 bcpassword 的 BCrypt 值:
$ brew tap spring-io/tap
$ brew install spring-boot
$ spring encodepassword bcpassword
{bcrypt}$2a$10$fJc2wH.Oc1SES8Ju/fCoFOjqs6CRnIgPAbUXqRJQ.DGnBVTGG.bLy
更新数据库里的 password 为$2a$10$fJc2wH.Oc1SES8Ju/fCoFOjqs6CRnIgPAbUXqRJQ.DGnBVTGG.bLy
。
设置 cas.authn.mongo.password-encoder.type=BCRYPT
注释掉 cas.authn.mongo.password-encoder.encoding-algorithm。
重新使用新配置启动 cas server,用密码 bcpassword 登录。这个时候 cas 后台就已经使用 BCrypt 来验证密码了。./gradlew clean copyCasConfiguration build run
其实 Type=BCRYPT 就对应到了 class org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder。
5)使用多个不同的 DataSource 用于认证
可同时使用多个不同的 DataSource 用于认证,但是相同类型的数据源只能有一个。
对于同时使用多个认证源的情况,关键是要设置好 authentication policy。请参考:Authentication Manager 和 Authentication Policy
。
同时用 json file, texfile,MongoDB 作为认证源的一个例子。
如果需要同时设置两个 MongoDB 作为认证源,就需要自己通过继承 AbstractUsernamePasswordAuthenticationHandler 来实现了。
_References_:
[1]: https://apereo.github.io/cas/6.5.x/authentication/Configuring-Authentication-Components.html
[2]: https://apereo.github.io/cas/6.5.x/authentication/Configuring-Authentication-Policy.html
[2]: https://fawnoos.com/2018/06/12/cas53-authn-handlers/