Realm接口的继承结构:
上一篇文章中,我是用ini文件来模拟数据源,但在实际开发中,我们常常需要自定义Realm来从数据库中查询数据并返回结果,通常情况下,我们继承AuthorizingRealm类即可,下面就是一个自定义Realm的例子:
package com.js.realm;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
/**
* 自定义realm
* @author jiangs
*
*/
public class CustomRealm extends AuthorizingRealm {
// 设置realm的名称
@Override
public void setName(String name) {
super.setName("customRealm");
}
/**
* 用于认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 1、从token中取出用户的身份信息
String usercode = (String)token.getPrincipal();
// 2、根据用户输入的账号从数据库中去查询,;此处模拟找出了password
String password = "11111";
// 3、如果查询不到,返回null;
// 4、如果查询到,返回认证信息
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(usercode, password, this.getName());
return simpleAuthenticationInfo;
}
/**
* 用于授权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// TODO Auto-generated method stub
return null;
}
}