shiro-realm认证

来源:互联网 发布:免费淘宝号和密码大全 编辑:程序博客网 时间:2024/06/06 09:45

        在前面我们已经提到过,在shiro的认证过程中,我们是将用户名和密码都配置到配置文件中。但是这样会极大的不方面我们的开发,比如说我们要添加或者修改个用户,还得去配置文件中修改,得在重新发布程序,非常的麻烦。不过在shiro中,不用在担心这个问题了,因为它已经给我们提供了一个和数据库交互的功能。这就是realm。下面来看下面的实例:

1、新建Realm

/** * 自定义realm * @author liujie * */public class CustomRealm extends AuthorizingRealm {    //设置realm的名称    @Override    public void setName(String name) {        super.setName("customRealm");    }        //用于授权    @Override    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {        // TODO Auto-generated method stub        return null;    }    //用于认证    @Override    protected AuthenticationInfo doGetAuthenticationInfo(            AuthenticationToken token) throws AuthenticationException {        // token是用户输入的        //第一步从token中取出身份信息        String userCode=(String)token.getPrincipal();        //        if (!userCode.equals("zhangsansan")) {//            return null;//        }        //第二步:根据用户输入的userCode从数据库查询        //。。。。。。        //模拟从数据库查询到的密码        String password="1111112";                //如果查询不到返回null                //如果查询到返回认证信息AuthenticationInfo                SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(                userCode, password, this.getName());                return simpleAuthenticationInfo;    }}

2、告诉shiro应用我们自己定义的Realm

[main]#自定义realmcustomRealm=cn.itcast.shiro.realm.CustomRealm#将realm设置到securityManager,相当于spring中注入securityManager.realms=$customRealm  

3、测试我们的功能

public class AuthenticationTest {    /**     * 自定义realm     * 用户登录     */    @Test    public void testCustomRealm(){        //创建securityManager工厂,通过ini配置文件创建securityManager工厂        Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro-realm.ini");        //创建SecurityManager        SecurityManager securityManager=factory.getInstance();        //将securityManager设置到当前的运行环境中        SecurityUtils.setSecurityManager(securityManager);;        //从SecurityUtils里边创建一个subject        Subject subject=SecurityUtils.getSubject();        //在认证提交前准备token(令牌)        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "111111");        try {            //执行认证提交            subject.login(token);        } catch (Exception e) {            // TODO: handle exception        }                //是否认证通过        boolean isAuthenticated=subject.isAuthenticated();                System.out.println("是否认证通过:"+isAuthenticated);            }}

1 0
原创粉丝点击