在Grails中使用Shiro安全框架

阅读更多
先安装插件 shiro-1.1.4

然后初始化(windows环境参数要加冒号,其它环境不用)
cd myoa
grails shiro-quick-start "--prefix=myoa."

会创建或修改以下文件 先允许修改,然后再用idea的diff功能人工整合
| Environment set to development.....
> User.groovy already exists. Overwrite? [y/n] y
| Created file grails-app/domain/myoa/User.groovy
| Created file grails-app/domain/myoa/Role.groovy
| Created file grails-app/realms/myoa/DbRealm.groovy
| Created file grails-app/controllers/myoa/AuthController.groovy
| Created file grails-app/views/auth/login.gsp
> SecurityFilters.groovy already exists. Overwrite? [y/n] y
| Created file grails-app/conf/myoa/SecurityFilters.groovy

半路出家的麻烦
因为系统已经开发了一段时间,已经有一个User对象,当时用的属性名“name/password”;而shrio也会生成一个User对象,用的“username/passwordHash”。

权衡之后,重构原来的User对象动静太大,还是重构shrio生成出来的文件吧,发现倒是不难:
1. login.gsp 不需要修改,因为会有一个token对象介于gsp和User对象之间
2. AuthController 不需要修改,只需要加一句把user对象存入session的,因为我的gsp大多用到了这个对象:SessionTool.loginUser = User.findByName(authToken.username)
3. DbRealm.groovy 修改User部分的引用,其它不用改

小有点成就感
花了1天时间,基本掌握了shiro框架,控制可以依赖框架,但权限需要自己设计
花了2天时间,可以从系统自动生成所有controller、action的权限表,然后设计了UI界面方便编辑和管理。
在Grails中使用Shiro安全框架_第1张图片



修改密码加密算法
The default realm basically hashes the password provided in the authentication token using SHA256 and then compares the hash to the password hash stored in the user domain instance.
If the hashes are the same, the user is authenticated. Now, SHA256 has known vulnerabilities, so you may want to use something a little more secure. If that's the case, you need to do two things.

First, when you create a user (such as in BootStrap ) you need to hash the password using the alternative algorithm
new Sha512Hash("password").toHex()

Second, you need to override the credentialMatcher bean, for example by adding the following to your grails-app/conf/spring/resources.groovy file:
import org.apache.shiro.authc.credential.Sha512CredentialsMatcherbeans = {
    credentialMatcher(Sha512CredentialsMatcher) {
        storedCredentialsHexEncoded = true
    }
    …
}
  • 在Grails中使用Shiro安全框架_第2张图片
  • 大小: 52.4 KB
  • 查看图片附件

你可能感兴趣的:(Grails,Shiro,安全)